Taking multiple orders on a Cafe program, along with a loop - python

I am currently trying to work on this python school assignment, and I'm lost at how to add a loop to continue ordering, and how to take orders of both coffee and tea. My program only lets you take an order of one, tea or coffee. My except ValueError also causes the order of adding vanilla syrup to the medium and large coffee not unique, and lets it be added to the small coffee as well, when it shouldn't. I am having a lot of trouble with this, and would really appreciate any help or suggestions to as what I could add/try
This is my code:
price = 0
print("Tea is 1, Coffee is 2.")
print("Small is 1, Medium is 2, Large is 3.")
try:
drinkchoice=float(input("What drink would you like?: "))
if(drinkchoice == 1):
TeaAmount=float(input("How many would you like?: "))
else:
CoffeeAmount=float(input("How many would you like?: "))
except ValueError:
print("Error, follow the directions!")
exit()
try:
drinksize=float(input("What size would you like?: "))
if(drinksize == 3 and drinkchoice == 1):
print("1 for yes, 2 for no")
Oprah=float(input("Would you like the Oprah sponsered option for 0.75 more?: "))
if(drinksize == 2 or 3 and drinkchoice == 2):
print("1 for yes, 2 for no")
vanilla=float(input("Would you like a shot of vanilla syurp for 0.50 more?: "))
except ValueError:
print("Error, follow the directions!")
exit()
if(drinkchoice == 1):
if(drinksize == 1):
price=price+2*TeaAmount
if(drinksize == 2):
price=price+3.50*TeaAmount
if(drinksize == 3):
price=price+4.65*TeaAmount
if(Oprah == 1):
teaPrice=round(price,2)
price=price+.75*TeaAmount
OprahPrice=.75*TeaAmount
else:
price=round(price,2)
coffeePrice = 0
vanillaPrice = 0
if(drinkchoice ==2):
if(drinksize == 1):
price=price+2.25*CoffeeAmount
if(drinksize == 2):
price=price+3.75*CoffeeAmount
if(vanilla == 1):
coffeePrice = round(price,2)
price=price+.50*CoffeeAmount
vanillaPrice=.50*CoffeeAmount
else:
price=round(price,2)
vanillaPrice=0
if(drinksize == 3):
price=price+4.85*CoffeeAmount
if(vanilla == 1):
coffeePrice = round(price,2)
price=price+.50*CoffeeAmount
vanillaPrice=.50*CoffeeAmount
else:
price=round(price,2)
vanillaPrice=0
teaPrice = 0
OprahPrice = 0
price = round(price,2)
print("You paid $", teaPrice, "for tea")
print("You paid $", coffeePrice, "for coffee")
print("You paid $", OprahPrice, "for the extra Oprah version")
print("You paid $", vanillaPrice, "for the vanilla syrup")
print("Your bill is $", price)
Here is the assignment

Leaving this as an answer as its too big for a comment.
With the structure of your data you will be much more suited to use a dictionary. This will make your code much easier to read, structure your data better and better support the addition of new drinks and new drink sizes in the future.
Dictionaries store a key and a value which can be called later by dict[key] or dict.get(key).
An example of storing this data could be;
drinks = {'tea': {'small': 1, 'medium': 2, 'large': 3}}
Now when a user specifies what they want, your life and code becomes much easier to manage and understand.
drinks['tea']['small']
#1
However, if tea does not exist, this method of calling your key, value pair would return a KeyError, so it may be better to use get() instead.
drinks.get('tea', {}).get('small')
#1
In the case either key here does not exist, this line will return None which provides a safe method to call your values.
You can also store your drink_options in a dictionary too. When you need to change pricing, just change the value of the key pair in your dict.
For your looping, while True: is a good way to continually loop until a user specifies to stop. It needs to be noted though, if you do not break out of this loop, it would run indefinitely.
You can use break to exit your while loop.
Below you can find some links on some reading which may help you learn more relating to this assignment. Happy learning!
Links
Python Official Documentation - Dictionaries
Python Official Documentation - Break & continue statements
While Loops
Dictionaries 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: ")

How do I make a validation loop to make sure the user inputs the correct amount of times in a .split input?

This may be kind of stupid but I've made a really roundabout way of validating a credit card number. I'm still really new at python and coding in general and wanted to make it so that I can validate the amount of digits, whether or not the input is numbers, and to also make it so I can print the input split up like this: xxx-xxxx-xxxx
So far I have this (please excuse how messy and probably unnecessary a lot of it is!)
CreditOne = 0
CreditTwo = 0
CreditThree = 0
while True:
CreditOne, CreditTwo, CreditThree = input("Enter the credit card number (separate with spaces): ").split()
CreditCardList = [CreditOne, CreditTwo, CreditThree]
CreditCardNumber = "-".join(CreditCardList)
if CreditOne.isdigit() and CreditTwo.isdigit() and CreditThree.isdigit() and len(CreditOne) == 4 and len(CreditTwo) == 4 and len(CreditThree) == 4:
break
elif CreditOne == 0 or CreditTwo == 0 or CreditThree == 0:
print("Please input a valid credit card number.")
continue
else:
print("Please input a valid credit card number.")
continue
print(CreditCardNumber)
It does the job for the most part except for the fact that if the user just inputs something like 4 4 or like a singular letter it will get a ValueError:
ValueError: not enough values to unpack (expected 3, got 1)
Basically what I've been trying to do is create a validation that allows the loop to continue after the error and return to the start of the loop. I've tried a try except loop and it didn't work, I wanted to get a second opinion on this and maybe some help from somebody who understands what I'm trying to achieve with my code.
Instead of unpacking first, then combining them into a list, do it the other way around:
CreditCardList = input("Enter the credit card number (separate with spaces): ").split()
if len(CreditCardList) == 3:
CreditOne, CreditTwo, CreditThree = CreditCardList
# ... do other stuff
else:
print("You must enter exactly 3 numbers")
As a side note, study generator expressions, list comprehensions and built-ins such as all and any to further simplify your code. For example, the following line:
if CreditOne.isdigit() and CreditTwo.isdigit() and CreditThree.isdigit() and len(CreditOne) == 4 and len(CreditTwo) == 4 and len(CreditThree) == 4:
can be rewritten as
if all(c.isdigit() and len(c) == 4 for c in CreditCardList):
Another way you could do this is with exceptions - this will help you deal with other errors as well:
while True:
try:
CreditOne, CreditTwo, CreditThree = input("Enter the credit card number (separate with spaces): ").split()
break
except ValueError:
print('Oops! That's not a valid number')

Why does my code print less "i" 's than the amount its supposed to be?

people = int(input("give me the amount of people who want to auction(must be less than 101 and more than 0"))
if people < 1:
print("you arn't so popular after all")
elif people > 100:
print("you were banned for having to much pepole")
else:
print(people)
for i in (0,people):
print("i")
if you put in a number like ten, it will only print 2 "i"'s
maybe because (0, people) is a tuple and only have two values: 0 and people.
I think it should be something like range(0, people).
Update
Yep, that was the case (it was a tuple), and according to the #CrazyChucky comment to this response a better way to do this could be:
for _ in range(people):
# do something here...

Why cant i sum up all of my values (user values) problem with while?

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.

H3lp High School Student With Python Loop

This is supposed to be code for a system in a store that loops again and again if someone wants to buy something else. Please help.
menu=["apple","water","juice"]
apple=50
water=80
juice=100
money=int(input("How much money in pennies do you have?"))
if money>=100:
print("We have the following items you can buy: apple, water, juice")
elif money>=80 and money<=100:
print("We have the following items you can buy: apple, water")
elif money>=50 and money<=80:
print("We have the following item you can buy: apple")
else:
print("Sorry, you can't buy anything.")
buy=input("What do you want to buy?")
if buy=="apple":
print("You have",money-50)
elif buy=="water":
print("You have",money-80)
else:
print("You have",money-100)
other=(input("Do you want to buy anything else?"))
if other=="yes":
while x=0:
print(x)
continue
elif other=="no":
x+1
else:
print("Error")
The last part doesn't work- can someone fix it so it does? This is Python 3- thanks.
problem fixed & loop optimized -
the problem you encountered was the extra brackets () around your input-function.
the loop is now optimized because your whole buying cycle is now inside this while True: loop. it will be repeated again and again until the user inputs something different then "yes" at the other question.
while True:
menu=["apple","water","juice"]
apple=50
water=80
juice=100
money=int(input("How much money in pennies do you have?"))
if money>=100:
print("We have the following items you can buy: apple, water, juice")
elif money>=80 and money<=100:
print("We have the following items you can buy: apple, water")
elif money>=50 and money<=80:
print("We have the following item you can buy: apple")
else:
print("Sorry, you can't buy anything.")
buy=input("What do you want to buy?")
if buy=="apple":
print("You have",money-50)
elif buy=="water":
print("You have",money-80)
else:
print("You have",money-100)
other=input("Do you want to buy anything else?")
if other=="yes":
continue
else:
break
other=(input("Do you want to buy anything else?"))
if other=="yes":
while x=0: <-- should use x==0, but x is not declared
print(x) <-- wrong indentation
continue
elif other=="no":
x+1 <-- even if x was declared, this only sum and nothing
else: more (nothing changes in your program)
print("Error")
This last part basically does nothing useful even if it worked. I suggest you to use the code posted in the other answer.

Categories