Why cant i get the total from a While true loop - python

I cant seem to get the total from my while true loop. I am trying to write a code . That will get the total value for all the seats a waiter enters. But I keep getting the total like this Total:$ q I had set q to break if the user input it for a seats. Can you help me please. Here is my syntax.
while True:
seats = raw_input("Enter the value of the seat [q to quit]:")
if seats == 'q':
break
print "Total: $", seats

total = 0
while True:
seats = raw_input("Enter the value of the seat [q to quit]:")
if seats == 'q':
break
total += int(seats)
print "Total: $", str(total)
If you want it to show the total after each loop just push the print statement inside the loop.

You need to sum variable seats with your input value, not reassigning value.
You were wrong in choosing operator, you need to use +=, not =.
Replace your code with this:
while True:
input = raw_input("Enter the value of the seat [q to quit]:")
if input == 'q':
break
seats += input
print "Total: $", seats
After that, read this question and answers:
What exactly does += do in python?

Related

I want to make a nested loop that makes user enter a number that does not make the input variable have a negative output. How with changing variable?

This is Python in Visual Studio Code. I'm making a program for school that essentially is an robotic restaurant waitress. I have to do it the way the assignment outline says which is why it might be a little weird. Then I have to personalize it and make it creative. It asks how much the price of an adult meal and a child meal. Then it asks how many children and adults there are. Then it asks what the sales tax rate is. The assignment only needs me to be able to calculate all that and get the subtotal and total and then give change. I've already done that and I'm making it fancy. I made a loop that asks if they have a lucky draw coupon that generates a random monetary value between $1.00-$5.00. Then If they say yes it will bring them to the first part of the loop that gives them the total with the coupon and then asks for payment. If they say no, then it just asks them for the payment.
I want to go the extra mile and put a loop in a loop, which I think is called a nested loop (This is my first week of Python.) I want it to recognize if the amount they pay is less then the total, then ask for the user to try again until they put an amount more than the total. Pretty much I just want it to know that the payment isn't enough.
My problem is I've never used nested loops and this is the first time I've even used a loop period. I also don't know how to make a loop based on a variable that's not constant because it's based on what the user inputs when prompted. I could do it if I could put the parameters in a fixed range, but the range will always be different based on what they enter in the beginning.
How do I make a nested loop recognize a variable that is never the same?
How do I make it recognize the payment is not enough to cover the total?
This is the loop I have. And I want to put two nested loops in the loop. One for if and one for elif so that it works for both "options".
Here is my snippet:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
payment = float(input("Please enter your payment amount: "))
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")
Any suggestions? I've searched all over Stackoverflow and google and cannot find anything specific to my situation.
Your approach is good for implementing this. Looping while asking for payment and validating that it is correct before allowing the loop to break will do the job. For your first if block, this is how that would look:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
#Ask for the payment inside of the new loop
while True:
payment = float(input("Please enter your payment amount: "))
if payment - total + coupon > 0:
print("That's not enough money to pay your bill. Try again")
else:
break
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")

Add numbers and exit with a sentinel

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)

Wack A Mole With Python Syntax/Punctuation

Alright, so I've been playing with this piece of code for a while. What I want it to do is:
a) if yes, continue to the next part of the program.
b) if no, return back to the questioniare to re-enter the proper data.
c) if neither, request a y/n answer again.
So right now this is what I have so far. I'm working out of Python 3.4.1, and at this point it is telling me "invalid syntax" on the last variable "answer" after the "else" statement. If I try to adjust this statement then it will go on to tell me that a colon is out of place, that the "elif" is "invalid syntax," and that the first "break" in the "if" statement is "out of the loop" due to indentation. So here's my question: where do I start debugging it since all of it seems to be confused?
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
answer = input('If this is correct please type: yes or no: ')
if answer == ('no'):
print('You said no! Darn, let me get those numbers again...')
break
elif answer == ('yes'):
print ('Great! Let us continue...')
continue
else answer != ('yes', 'no'):
print ('You did not answer correctly! Please try again: ')
break
Any and all answers will be greatly appreciated! :)
You can't specify a condition for an else (and in this context, it isn't logically needed anyway). Just do:
else:
print ('You did not answer correctly! Please try again: ')
Also, break isn't proper syntax for an if block, so remove all the breaks from your code. You're probably thinking of switch statements, which Python doesn't support.
First, your else is invalid for at least reasons: if you want to test a condition, you need elif; if you want to test whether answer is equal to neither of two values you need not in, not !=; etc. But you really have no reason to test anything here anyway. If you didn't do the if or the elif, you want to do the else.
Second, you're missing a while True: to go with those break and continue statements.
Also, you've got break and continue backward. A break breaks out of a loop, and moves on with the rest of the program; a continue continues to the next time through the loop.
So:
while True:
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
answer = input('If this is correct please type: yes or no: ')
if answer == ('no'):
print('You said no! Darn, let me get those numbers again...')
continue
elif answer == ('yes'):
print ('Great! Let us continue...')
break
else:
print ('You did not answer correctly! Please try again: ')
continue
There's still one problem left: You want the third choice to go back to just ask the last question again, not the whole thing. This means you need a loop inside a loop… and you can only break or continue one loop at a time. This is one of many reasons it's probably worth refactoring this into smaller functions, so you can just return when you're done. For example:
def yesno(prompt):
while True:
answer = input(prompt)
if answer == "no":
return False
elif answer == "yes":
return True
else:
print('You did not answer correctly! Please try again:')
def questionnaire():
while True:
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
if yesno('If this is correct please type: yes or no:'):
print('Great! Let us continue...')
return b, i, m
else:
print('You said no! Darn, let me get those numbers again...')
Notice I didn't need break or continue anywhere.
Unlike switch statements, if-elif-else statements are mutually exclusive so you don't need to break once you enter the block of code corresponding to that conditional branch. Also, else statements can not take conditions since they mean (if none of the above is true). The behaviour you describe is a loop, where a block of code is repeated until a certain condition is met. Using a flag (a boolean variable) and a while loop, you can run that block of code an arbitrary number of times until any of the conditions in the if-elif-else statements are met, at which point you change the value of the flag, which in turn terminates the loop. Here is an example using your code:
EDIT: I reread your specs and modified the code to make it re-ask for yes/no answer only instead of getting the first three inputs again.
move_on= False
while (!move_on):
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
answer = input('If this is correct please type: yes or no: ')
ask_again= True
while (ask_again):
if answer == 'no':
print('You said no! Darn, let me get those numbers again...')
ask_again= False
elif answer == 'yes':
print ('Great! Let us continue...')
ask_again= False
move_on=True
else:
print ('You did not answer correctly! Please try again: ')

Python Help, Max Number of Entries

Created a program for an assignment that requests we make a program that has the user input 20 numbers, and gives the highest, lowest etc. I have the main portion of the program working. I feel like an idiot asking this but I've tried everything setting the max number of entries and everything I've tried still lets the user submit more than 20. any help would be great! I tried max_numbers = 20 and then doing for _ in range(max_numbers) etc, but still no dice.
Code:
numbers = []
while True:
user_input = input("Enter a number: ")
if user_input == "":
break
try:
number = float(user_input)
except:
print('You have inputted a bad number')
else:
numbers.append(number)
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
Your question could be presented better, but from what you've said it looks like you need to modify the while condition.
while len(numbers) < 20:
user_input = input("Enter a number:" )
....
Now once you've appending 20 items to the numbers list, the script will break out of the while loop and you can print the max, min, mean etc.
Each time the user enters input, add 1 to a variable, as such:
numbers = []
entered = 0
while entered < 20:
user_input = input("Enter a number: ")
if user_input == "":
break
else:
numbers.append(number)
try:
number = float(user_input)
except:
print('You have inputted a bad number')
continue
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
entered+=1
Every time the while loop completes, 1 is added to the variable entered. Once entered = 20, the while loop breaks, and you can carry on with your program. Another way to do this is to check the length of the list numbers, since each time the loop completes you add a value to the list. You can call the length with the built-in function len(), which returns the length of a list or string:
>>> numbers = [1, 3, 5, 1, 23, 1, 532, 64, 84, 8]
>>> len(numbers)
10
NOTE: My observations were conducted from what I ascertained of your indenting, so there might be some misunderstandings. Next time, please try to indent appropriately.

How do I count the number of entries in a python code using while loops?

I'm working on a homework assignment for my introductory python programming class and I am stuck on a problem. The instructions are to:
Modify the find_sum() function so that it prints the average of the values entered. Unlike the average() function from before, we can’t use the len() function to find the length of the sequence; instead, you’ll have to introduce another variable to “count” the values as they are entered.
I am unsure on how to count the number of inputs and if anyone can give me a good starting point, that would be great!
# Finds the total of a sequence of numbers entered by user
def find_sum():
total = 0
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
total += int(entry)
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", total
Every time you read an input total += int(entry), immediately afterward you should increment a variable.
num += 1 is all it would take, after you've initialized it to 0 elsewhere.
Make sure your indentation level is the same for all statements in the while loop. Your post (as originally written) did not reflect any indentation.
You could always use an iteration counter as #BlackVegetable said:
# Finds the total of a sequence of numbers entered by user
def find_sum():
total, iterationCount = 0, 0 # multiple assignment
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
iterationCount += 1
total += int(entry)
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", total
print "Total numbers:", iterationCount
Or, you could add each number to a list and then print the sum AND the length:
# Finds the total of a sequence of numbers entered by user
def find_sum():
total = []
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
iterationCount += 1
total.append(int(entry))
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", sum(total)
print "Total numbers:", len(total)

Categories