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
Related
I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.
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 am starting to code a game just to practice. However, the user needs to enter an odd number to play. If they don't then I want the program to ask them for an odd number they loop and play again. I put this code in the else statement but if I enter an odd number it will not loop again.
Question 2:
how can I get the program to display Game 1, Game 2, etc as the loop runs however many times the input in 'Games' is?
Can someone help?
games = input("How many games would you like to play?")
for i in range(games):
if games % 2 == 1:
print('Game 1')
# code here
else:
input('Enter an odd number')
Try this:
games = int(input("How many games would you like to play?"))
while True:
if games % 2 == 1:
for i in range(games):
print('Game', i+1 )
break
else:
games = int(input('Enter an odd number: '))
It appears to me that you your confusion lies in a couple casting errors. Please note that input returns a type string, which you attempt to use as an integer. Try the following code instead:
games = input("How many games would you like to play? ")
numberOfGames = int(games)
for i in range(numberOfGames):
print('Processing Game ' + str(i))
testVal = input('Enter an odd number ')
if int(testVal) % 2 == 1:
print("Congratts! " + testVal + " is odd!\n\n")
else:
print("You Loose. " + testVal + " is even.\n\n")
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
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)