Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 learning to code python
#1
Hi guys,

I just started learning to code and using Python, I am working on a beginner exercise and the result is not what I am supposed to get, I am hoping you guys could point me in the right direction on how to correct it. I didn't get any error, but the last print line only printed out the the string "Calories content for and the date" but it does not print out the number of totalcal.
When I removed the str(today) from that line, it printed out the totalcal. If both str(today) + str(totalcal) are on the same line, then it would only printed out the value for str(today), so it would only be one or the other. What am I doing wrong? Thank you so much for your help, please let me know if you have any questions.

from datetime import date

today = date.today()
print("Today's date? " + str(today))

print("Breakfast Calories? ")
breakfast_cal = int(input())
print("Lunch Calories? ")
lunch_cal = int(input())
print("Dinner Calories? ")
dinner_cal = int(input())
print("Snack Calories? ")
snack_cal = int(input())

totalcal = breakfast_cal + lunch_cal + dinner_cal + snack_cal
print(totalcal)

print("Calories content for " + str(today) + str(totalcal) )
Quote
#2
Your code is printing out both the date and the total calories in the final line, but with no space between them (since you haven't indicated one in the code). There are tons of different ways of formatting print output and strings in python, but a simple change to your code to add a colon and space after the date would look like:
print("Calories content for " + str(today) + ': ' + str(totalcal))
Quote
#3
Hi, im too new in Python, but maybe you can try this

print("Calories content for ",str(today),str(totalcal))
or

print("Calories content for ",today," ",totalcal)
Quote
#4
OH!! THANK YOU!!! That's awesome, thank you so much! I can't believe I missed that.
Quote
#5
A good habit to get into with your output is to use f strings. By using the plus sign if today and totalcal were both numeric you would end up with the sum, which is clearly not intended.
print(f"Calorie content for {today} is approximately {totalcal}. You should eat less")
Very readable, less prone to error.
Quote
#6
Thanks Jefsummers, cool tips! I saw someone using the f string at another forum and didn't really understand how it works until now.
Also, just testing around to see the difference from using Dotspared's method above, if using the + sign from my original method, I would have to cast today and totalcal to string, otherwise, it would bombed out.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Learning python, stuck on some code. stanceworksv8 2 713 Apr-02-2019, 01:51 AM
Last Post: stanceworksv8
  Still learning - code efficiency, which of these is better? shelzmike 2 1,182 Oct-14-2017, 04:47 AM
Last Post: shelzmike

Forum Jump:


Users browsing this thread: 1 Guest(s)