Summing up numbers inside while function - python

The goal of the program is to ask user for input for a number of calories in given meal. Later I would like to add the numbers so that the program remembers the previous input. This is only part of the program, but later it returns back to user_input_calories so user can input calories as many times they want. Probably count_calories should not be zero. Could someone help me with that or add some references that I can take a look at?
start=input('Type add to add a meal:')
while start=='add' or start=='Add':
user_input_calories=input('Enter the number of calories in the meal:')
try:
nr1=int(user_input_calories)
count_calories=0
count_calories=count_calories+nr1
except:
print('You have finised eating for the day')
continue

Here's an example of what Matt Clark wrote in the comment:
start=input('Type add to add a meal: ')
count_calories=0 # Counter outside the loop
while start.lower() == 'add':
user_input_calories=input('Enter the number of calories in the meal (q to quit): ')
if user_input_calories == 'q': # Added a command to end the program and count the calories
print('You have finised eating for the day')
print(f'You ate: {count_calories} calories')
break
try:
user_input_calories = int(user_input_calories) # Try to convert to integer and add the value
count_calories += user_input_calories
except:
print("You didn't enter a number")
Result:
Type add to add a meal: add
Enter the number of calories in the meal (q to quit): 100
Enter the number of calories in the meal (q to quit): 200
Enter the number of calories in the meal (q to quit): 300
Enter the number of calories in the meal (q to quit): q
You have finised eating for the day
You ate: 600 calories

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: ")

I want to know how I can make it so that the code doesn't stop after the DEPOSIT if condition ends, how can I do that? (PYTHON)

I want to know how I can make it so that the code doesn't stop after the DEPOSIT if condition ends, but intead loops back to the input. How can I do that in Python?
This is my code:
print("Welcome to Doge Bank")
print("How much money would you like to start with?")
balance = int(input())
print("Great! You can type DEPOSIT to DEPOSIT money, BAL to check your BALANCE and WITHDRAW to WITHDRAW money")
operation = input()
if operation == "DEPOSIT":
print("You have started a deposit operation, say Y to continue")
confirm = input()
if confirm == "Y":
print("How much would you like to deposit?")
depositNum = int(input())
balance = balance - depositNum
print("You have deposited", depositNum, "| Your current balance is", balance)
Looks like your are building a prototype for an ATM machine. You could use a while loop like following. ‘while’ literally means keep on looping until the given condition is not violated. Your code ends because ‘if’ statement is not a ‘loop’. If the condition in ‘if’ is fulfilled (i.e if the user selects ‘DEPOSIT’ then the code under it is executed and then it does not ‘loop’)
print("Welcome to Doge Bank")
print("How much money would you like to start with?")
balance = int(input())
session_live = True
while session_live:
print("Great! You can type DEPOSIT to DEPOSIT money, BAL to check your BALANCE and WITHDRAW to WITHDRAW money, EXIT to exit.")
operation = input()
if operation == "DEPOSIT":
print("You have started a deposit operation, say Y to continue")
confirm = input()
if confirm == "Y":
print("How much would you like to deposit?")
depositNum = int(input())
balance = balance + depositNum
print("You have deposited", depositNum, "| Your current balance is", balance)
elif operation == "EXIT":
print("Thank you for using our ATM")
session_live = False
Here at first the variable session_live is set to True. It remains True unless you change it. The loop continues until you change session_live to False. In python when you say “while session_live:” it means ‘while session_live is True:’ and in fact you can write it as ‘while session_live is True:’To demonstrate changing the value of session_live, I added a condition where if the user selects “EXIT” then you change session_live to False.
Please note that in your code, you reduce the amount that was ‘deposited’ from the balance. Change that to ‘+’ instead of ‘-‘ as I have done here. You can similarly add other ‘elif’ conditions for ‘BALANCE’ and ‘WITHDRAW'

Python : Amount input with While

Beginner here. I'm trying to build a loop where the chekout displays a total amount that has to be over 0$. For example, if I start with 450$ the code works. But if I start with say -12 it will ask me again (which is what I want), but then if I enter 450 as the third essay; the first condition keeps runing. Why is that? Thanks in advance.
amount = input("What's the total amount of the bill ? :")
value = float(amount)
while (value < 0):
print("Please enter an amount higher than 0$ !")
amount = input("What's the total amount of the bill ? :")
else:
print("Total amount of the bill:{0}".format(value))
You forgot to update the variable "value" so your while loop condition remains true even after inputting 450 (value is still -12). You can convert the input to a float in the same line too, which removes the need for the "amount" variable
value = float(input("What's the total amount of the bill ? :"))
while (value < 0):
print("Please enter an amount higher than 0$ !")
value = float(input("What's the total amount of the bill ? :"))
else:
print("Total amount of the bill:{0}".format(value))

How can I loop a line of code until the user types the correct answer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am a beginner and i can't understand that how can I loop a line until the user types that correct answer and then it breaks. For ex.
ask = int(input("How much rice do you want? "))
price_of_1kg = 50
total = ask*price_of_1kg
print("This is the price")
print(f"Value: ${total}")
pay = int(input("Pay this price mentioned above "))
while True:
if pay == total:
print("good")
break
if pay != total:
int(input("Hey!! Pay the exact amount "))
break
print("Thank you, visit again")
```
I want to loop the second if statement until the user enters the correct amount
you can do it like this:
ask = int(input("How much rice do you want? "))
price_of_1kg = 50
total = ask*price_of_1kg
print("This is the price")
print(f"Value: ${total}")
pay = int(input("Pay this price mentioned above "))
while pay != total:
pay = int(input("Hey!! Pay the exact amount "))
print("Thank you, visit again")

Hello There, trying to make this program continuously loop until they input a valid selection from the first menu

trying to make this program continuously loop until they input a valid selection from the first menu, options 1-6. So far I it only will only ask 1 more time and then if they input an invalid character it goes straight to terminate message. For a class I'm taking and very new to this program.
Any help would be appreciated. I did notice that if I post the
if Choice not in [1,2,3,4,5,6]:
print ("\n",Choice, "is not a valid choice.\n")
print ("Please select choose from the available options.\n")
menu()
Choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): "))
section after elif Choice==6 it will loop another time but that's it.
# Imperial - Metric Conversion Calculator
# This Program Calculates the conversions from Imperial to Metric units
# or Metric to Imperial units. Users first select the type of conversion
# they wish to execute, then they enter their value and the program converts
# it. They will then be asked if they wish to execute another conversion,
# if yes the process would be repeated, if no the program will terminate.
#
# N = Number of Units, for the calculation
# R = Result from calculation
# Initialization
terminate = False
while not terminate:
# Welcome Message
print("\n""Created By Name \n")
# Instructions
print("Welcome to the Imperial/Metric Conversion Calculator,")
print("please select the type of Conversion you would like to")
print("perform from the list.\n")
# Define Menu
def menu():
print("1.Ounces to Grams Conversion.\n")
print("2.Grams to Ounces Conversion.\n")
print("3.Inches to Centimeters Conversion.\n")
print("4.Centimeters to Inches Conversion.\n")
print("5.Miles to Kilometers Conversion.\n")
print("6.Kilometers to Miles Conversion.\n\n")
menu()
# User Choice Input
Choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): "))
# Calculations, if/elif Statements, Output
if Choice not in [1,2,3,4,5,6]:
print ("\n",Choice, "is not a valid choice.\n")
print ("Please select choose from the available options.\n")
menu()
Choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): "))
# Process User Input, Display Result, Ounces to Grams
if Choice==1:
N = float(input("\n""Please enter the Number of Ounces: "))
R = N * (28.3495231)
print('\n \n'"Based on the units you entered the conversion from Ounces to Grams is {:,.2f}".format(R))
# Process User Input, Display Result, Grams to Ounces
elif Choice==2:
N = float(input("\n""Please enter the number of Grams?: "))
R = N / (28.3495231)
print('\n \n'"Based on the units you entered the conversion from Grams to Ounces is {:,.2f}".format(R))
# Process User Input, Display Result, Inches to Centimeters
elif Choice==3:
N = float(input("\n""Please enter the number of Inches?: "))
R = N * (2.54)
print('\n \n'"Based on the units you entered the conversion from Inches to Centimeters is {:,.2f}".format(R))
# Process User Input, Display Result, Centimeters to Inches
elif Choice==4:
N = float(input("\n""Please enter the number of Centimeters?: "))
R = N / (2.54)
print('\n \n'"Based on the units you entered the conversion from Centimeters to Inches is {:,.2f}".format(R))
# Process User Input, Display Result, Miles to Kilometers
elif Choice==5:
N = float(input("\n""Please enter the number of Miles?: "))
R = N * (1.609344)
print('\n \n'"Based on the units you entered the conversion from Miles to Kilometers is {:,.2f}".format(R))
# Process User Input, Display Result, Kilometers to Miles
elif Choice==6:
N = float(input("\n""Please enter the number of Kilometers?: "))
R = N / (1.609344)
print('\n \n'"Based on the units you entered the conversion from Kilometers to Miles is {:,.2f}".format(R))
# Thank You Message
print('\n\n'"Thank you for using the Imperial - Metric Conversion Calculator! \n")
# Terminate Check
response =input("Would you like to perform another conversion? (y/n): ")
while response != 'y' and response != 'n':
response = input("Please enter 'y' or 'n' : ")
if response == "n" :
terminate = True
You can try this:
while True:
try:
choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): ")))
if choice not in [1, 2, 3, 4, 5, 6]:
raise ValueError
break
except ValueError:
print ("\n",Choice, "is not a valid choice.\n")
print ("Please select choose from the available options.\n")
menu()
Does this help?

Categories