I'm writing a simple python program that helps users keep track of the number of calories that they consume and displaying whether the user is over or within their calorie goal for the day.
Here's my code so far.
caloriesGoal = float(input('Enter the calorie goal for number of calories for today: '))
numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today'))
totalConsumed = 0
while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000):
numberOfCaloriesConsumed = float(input('How many calories did you consumed?'))
totalConsumed += numberOfCaloriesConsumed
count = count + 1
print('Your total calories consumed is: ' , totalConsumed)
if(caloriesGoal > totalConsumed):
print('The user is within their goal by ', (caloriesGoal - totalConsumed))
else:
print('The user exceeded their goal by', (totalConsumed - caloriesGoal))
Try this out, the output is much clearer for what you are expected to enter.
while True:
caloriesGoal = float(input('Enter the calorie goal the day: '))
if 1500 <= caloriesGoal <= 3000:
break
else:
print("Error: Goal must be between 1500 and 3000 calories!")
totalConsumed = 0
items = 0
while True:
caloriesConsumed = float(input('Item {}: How many calories was it? (-1 to stop)'.format(items+1)))
if caloriesConsumed < 0:
print("Input stopped")
break
totalConsumed += caloriesConsumed
items += 1
if totalConsumed > caloriesGoal:
print("Goal reached/exceeded!")
break
print('You consumed {} calories in {} items.'.format(totalConsumed, items))
if caloriesGoal > totalConsumed:
print('The user is within their goal by ', (caloriesGoal - totalConsumed))
else:
print('The user exceeded their goal by', (totalConsumed - caloriesGoal))
Welcome to Python! It was my second language, but I love it like it was my first. There are few things going on in your code that's a little strange.
Something interesting is that you're doing a check on numberOfCaloriesConsumed. If you're entering a Krispy Kreme donut, you're going to enter 190 calories. Let's review your while:
while (numberOfCaloriesConsumed > 1500 and numberOfCaloriesConsumed < 3000):
If we take a look at this line ...
numberOfCaloriesConsumed = float(input('Enter the number of calories consumed today'))
... and we enter 190 for our Krispy Kreme donut, then we won't enter the loop. What you may want to change the while to is an infinite loop with a break mechanism:
while 1:
numberOfCaloriesConsumed = input('How many calories did you consumed?')
if (numberOfCaloriesConsumed == "q") or (totalConsumed > 3000): # keep numberOfCaloriesConsumed as a string, to compare for the break
if (totalConsumed < 1500):
print("You need to eat more!\n")
else:
break
else:
if (totalConsumed + int(numberOfCaloriesConsumed)) > 3000:
print("You eat too much! You're done now!\n")
break
totalConsumed = totalConsumed + int(numberOfCaloriesConsumed) #make the string an int, if we're adding it
This way, the code loop is exited when your user manually exits the loop (or if they've entered too many calories). Now, your user should be able to input caloric data and have it added up for them.
Also, I would remove the counter because the counter isn't necessary for this loop. We've got a few reasons why we don't need the counter:
The counter isn't directly affecting the loop (e.g. no while counter < 5)
We have the computer asking for user input, so the program stops and gives control to the human thus no infinite loop
We have break statements to remove us from the (new) loop
Related
I'm having an issue with my program. I'm working on a program that lets you play a small game of guessing the correct number. The problem is if you guess the correct number it will not print out: "You guessed it correctly". The program will not continue and will stay stuck on the correct number. This only happens if you have to guess multiple times. I've tried changing the else to a break command but it didn't work.
Is there anyone with a suggestion?
This is what I use to test it:
smallest number: 1
biggest number: 10
how many times can u guess: 10
If you try to guess the correct number two or three times (maybe more if u need more guesses) it will not print out you won.
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
#while loop until the guess is the same as the random number
while guess != x:
#this is if u guessed to much u get the error that you've guessed to much
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else: print("\n \nYou Lost, You've guessed", x, "times\n")
break
#this part is not working, only if you guess it at the first time. it should also print this if you guessed it in 3 times
else: print("You guessed it correctly", x)
test = (input("this is just a test if it continues out of the loop "))
print(test)
The main issue is that once guess == x and count < amount you have a while loop running that will never stop, since you don't take new inputs. At that point, you should break out of the loop, which will also conclude the outer loop
You can do it simply by using one while loop as follows:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#this is if u guessed too much u get the error that you've guessed too much
while count <= amount:
guess = int(input("guess the number: "))
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
if guess!=x:
print("\n \nYou Lost, You've guessed", count, "times\n")
As Lukas says, you've kind of created a situation where you get into a loop you can never escape because you don't ask again.
One common pattern you could try is to deliberately make a while loop that will run and run, until you explicitly break out of it (either because the player has guessed too many times, or because they guessed correctly). Also, you can get away with only asking for a guess in one part of your code, inside that while loop, rather than in a few places.
Here's my tweak to your code - one of lots of ways of doing what you want to:
import random
#counts the mistakes
count = 0
#asks to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#asks how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#while loop until the guess is the same as the random number
while True:
if count < amount:
guess = int(input("guess the number: "))
#this is if u guessed to much u get the error that you've guessed to much
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("\n \nYou Lost, You've guessed", x, "times\n")
PS: You got pretty close to making it work, so nice one for getting as far as you did!
This condition is never checked again when the guessed number is correct so the program hangs:
while guess != x:
How about you check for equality as the first condition and break out of the loop if true:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
if guess == x:
print("You guessed it correctly", x)
else:
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("You guessed too many times")
I'm learning beginner python and there's one question that I'm stuck on.
The question involves asking user input for any amount of mushrooms that they have picked, entering a weight, and then sorting them according to the user input. For this, a list and a while loop is needed to append the inputs into the list.
Here is my code so far, which works well with being able to enter all the user values, but gets stuck later on.
if __name__ == "__main__":
total_list = []
small = 0
medium = 0
large = 0
while True:
try:
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
total_list.append(mushroom)
if mushroom <= 100:
small += 1
elif mushroom >= 1000:
large += 1
else:
medium += 1
except STOP:
break
print("The weights you entered were ", total_list)
print("There were", small, "small mushrooms,", medium, "mediums, and", large, "larges.")
The error occurs on line 24, where STOP conflicts with the input requirement int().
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
ValueError: invalid literal for int() with base 10: 'STOP'
How can I fix the issue to make sure that STOP is my sentinel value, and will break the while loop and print the two statements later?
Thank you.
I've got the task of looping a function that allows for an imaginary person to spend up to £100 or whatever currency until the 100 runs out in which case the script just ends. While the script is running it adds up each of the values and keeps track until the threshold is met!
#This line should initialise a variable
while #I need Finish this line with a loop condition.
x = int( input("How much is the next item? ") )
tot = tot+x
print("You cannot afford that! You only have £" + str(100-(tot-x)) + "
while True:
do_stuff()
if you_want_to_stop:
break
tot = 0
while True:
x = int( input("How much is the next item? ") )
if (tot+x)>100:
print("You cannot afford that! You only have £ {}".format(str(100-(tot))))
continue #you want to skip this iteration and repeat
if tot==100:
print("You cannot afford more!")
break #you want to stop
tot += x
New to this so please bear with me. I'm trying to run a loop that asks the user to input a number between 1 and 100. I want to make it to where if they enter a number outside of 100 it asks again. I was able to do so but I can't figure out if I'm using the correct loop. Also whenever I do get inbetween 1 and 100 the loop continues.
code below:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
else:
while user_input > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
I think the clearest way to do this is to start with a loop that you break out of when you finally get the right answer. Be sure to handle a bad input like "fubar" that isn't an integer
while True:
try:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
break
print("Not between 1 and 100, try again")
except ValueError:
print("Not a number, try again")
In python 3 you can use range to do bounds checking. If you do
if user_input in range(1, 101)
range will calculate the result without actually generating all of the numbers.
When your code is run, it will continue to ask for an input, even if the input given is less than 100. One way to fix this would be to do this:
try_again = 1000
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
elif user_input > 100:
while try_again > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
This code first tests if the user's input is more than 100, then runs a while statement in which the base value is more than 100. When the user inputs another value, if it is over 100, it continues, otherwise it does not.
Below is an example of a program that gets you the output that you are seeking:
attempts = 0
while True:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input > 100 or user_input < 1:
print('Please try again')
attempts += 1
continue
elif attempts >= 1 and user_input <= 100 and user_input >= 1:
print('There you go!')
break
else:
print('Nice!')
break
Start by putting your prompt for the user within the loop so that the user can be asked the same prompt if the fail to enter a number between 1 and 100 the first time. If the user input is greater than 100 or less than 1, we will tell the user to try again, we will add 1 to attempts and we will add a continue statement which starts the code again at the top of the while loop. Next we add an elif statement. If they've already attempted the prompt and failed (attempts >= 1) and if the new input is less than or equal to 100 AND the user input is also greater than or equal to 1, then the user will get the 'There you go' message that you assigned to them. Then we will break out of the loop with a break statement in order to avoid an infinite loop. Lastly we add an else statement. If the user satisfies the prior conditions on the first attempt, we will print 'Nice' and simply break out of the loop.
My assignment is to add up a series of numbers using a loop, and that loop requires the sentinel value of 0 for it to stop. It should then display the total numbers added. So far, my code is:
total = 0
print("Enter a number or 0 to quit: ")
while True:
number = int(input("Enter a number or 0 to quit: "))
print("Enter a number or 0 to quit: ")
if number == 0:
break
total = total + number
print ("The total number is", total)
Yet when I run it, it doesn't print the total number after I enter 0. It just prints "Enter a number or 0 to quit", though it's not an infinite loop.
The main reason your code is not working is because break ends the innermost loop (in this case your while loop) immediately, and thus your lines of code after the break will not be executed.
This can easily be fixed using the methods others have pointed out, but I'd like to suggest changing your while loop's structure a little.
Currently you are using:
while True:
if <condition>:
break
Rather than:
while <opposite condition>:
You might have a reason for this, but it's not visible from the code you've provided us.
If we change your code to use the latter structure, that alone will simplify the program and fix the main problem.
You also print "Enter a number or 0 to quit:" multiple times, which is unnecessary. You can just pass it to the input and that's enough.
total = 0
number = None
while number != 0:
number = int(input("Enter a number or 0 to quit: "))
total += number # Same as: total = total + number
print("The total number is", total)
The only "downside" (just cosmetics) is that we need to define number before the loop.
Also notice that we want to print the total number after the whole loop is finished, thus the print at the end is unindented and will not be executed on every cycle of the while loop.
You should sum the numbers inside the loop even if they aren't zeros, but print the total after the loop is over, not inside it:
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
If the number is 0, the first thing you are doing is break, which will end the loop.
You're also not adding the number to the total unless it's 0, which is not what you're after.
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
You were very near, but you had some indentation problem.
Firstly, why all these print statements? I guess you are trying to print it before taking input. For this, the below line will be enough.
number = int(input("Enter a number or 0 to quit: "))
Secondly, differentiate between what you want to do, when only the number==0 and what to do in every iteration.
You want to use the below instruction in every iteration as you want every number to be added with total. So, keep it outside if block.
total = total + number
And when number==0, you first want to print something and then break the loop.
if number == 0:
print ("The total number is", total)
break
Make sure you are adding with total first and then checking the if condition, because once you break the loop, you just can't add the number to total later.
So, the solution could be like that,
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
print ("The total number is", total)
break
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
if number == 0:
break
total = total + number
print("The total number is", total)
If you put break before your other code, then the loop will be ended and your code after that break will not run.
And by the way, you can use try...except to catch the error if user didn't enter a number:
total = 0
while True:
try:
number = int(input("Enter a number or 0 to quit: "))
except ValueError:
print('Please enter a number')
continue
if number == 0:
break
total = total + number
print("The total number is", total)