Python : Amount input with While - python

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

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

My while loop is keeps looping. What am I doing wrong?

In this the total amount is the amount the user need to pay. If user pay lesser than the total amount the system needs to subtract the payment and show their balance and keep on looping until the payment is completed. But, when I run my codes its keep on looping while showing the balance.
print ("Your total amount is:", total_amount)
print ("")
payment = int(input("Please insert your payment: "))
count = 0
while payment != total_amount:
count = total_amount - payment
print ("Your balance:", count)
payment = int(input("Please insert your payment: "))
if payment == total_amount:
print ("Successful")
does the program outputs "Successful" if the user inputs the total amount on the first input?
if the user doesnt input the total amount on the first input, what could happen is that the variable named payment will never be equal to the total payment, but the count will eventually reach the total amount yes, but the while loop does not has variable count working is logic statement, it uses payment as the variable for its logic. if someones buys a something from a store, and the total is 5 dollars,, and the buyer has 1 dollar bills, the buyer will first put one dollar on the counter, then the other 1, and so on... but the buyer will not put 1 dollar on the counter, and then 5 dollars on the counter, because that would be 6 dollars
You are not updating either payment or total_amount correctly in the loop. I believe this should work.
payment = int(input("Please insert your payment: "))
while payment <= total_amount:
diff = total_amount - payment
print("Your balance:", diff)
payment += int(input("Please insert your payment: "))
if payment == total_amount:
print("Successful")
 Based on your code, only if I pay the correct amount in one go, should I successfully pay. Of course this is wrong. I have modified and added some details to your code like this:
print("Your total amount is: $%.2f \n" % (total_amount))
count = 0
while count < total_amount:
payment = int(input("Please insert your payment: $"))
count += payment
print ("Your balance: $%.2f" % (total_amount - count))
print("Successful")
if count > total:
print("Your change is $%.2f" % (count - total))

Mathmatical Average Calculation

Edit the program provided so that it receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program should print:
The Average and The Sum
I've been able to get it to print the sum of the numbers put in but I think it is messing up when trying to calculate the average. I really need some help with this. try inputting 100 59 37 21 and you will see what I mean
data = input("Enter a number: ")
number = float(data)
while data != "":
number = float(data)
theSum += number
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum // number
print("The average is", average)```
As Mat and Nagyl have pointed out in the comments you need to keep track of how many numbers were given and divide the sum by that to get the average
data = input("Enter a number: ")
number = float(data)
numbersGiven = 0
theSum = 0
while data != "":
number = float(data)
theSum += number
numbersGiven += 1
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum / numbersGiven
print("The average is", average)
Notice that the first input isn't counted (I start with numbersGiven = 0) but the empty input at the end is counted so it gives the correct count.
you can use these code too!
instead of writing the formula for average you can use statistics module
import statistics
the code below asks you the numbers how many times you wrote in the number of datas
number_of_datas=int(input("number of inputs asking: "))
datas=[]
The following code takes the number from the number of times you wrote in the number of inputs
also you can write a Specified number instead of getting an input
for i in range(number_of_datas):
data = float(input("Enter a number: "))
datas.append(data)
fmean is float average
average=statistics.fmean(datas)
print(average)

How do I use a python table?

I was requested by my teacher to write a program in python which would require visitors of said attraction to insert the number of family members they are visiting with, and based off of that, have them know the admission fee. The admission fees given were $25 for anybody under 16, and 40 for anybody over 40.
This is what I've got so far:
def main():
admission = 0
print("Welcome to Wally World - use this program to calculate your admission fees")
number = int(input("How many members will you be taking with you? "))
members = {}
for n in range(0,number):
age = int(input("Please enter your ages: "))
if age <= 16:
admission = 25
if age > 16:
admission = 40
main()
How would I go about grabbing said admission values and adding them all together?
Thank you!
There is no need to use members = {}
Admissions can be added with only single line conditional statement (ternary if-else).
Check whether number of person is not negative or zero (I've used exit() in this case).
Check whether age is not negative (I've put pass you may call your program again using main() or exit using exit()).
Here is the working code:
def main():
admission = 0
print("Welcome to Wally World - use this program to calculate your admission fees")
number = int(input("How many members will you be taking with you? "))
if number < 0: exit()
for n in range(0,number):
age = int(input("Please enter your ages: "))
admission += (25 if age <= 16 and age > -1 else 40 if age> 16 else 0)
return admission
main()

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)

Categories