How to loop same variable with different result - python

Hi I've got a school project which requires me to code a program that asks a user for their details it will then ask what them what size pizza they want and how many ingredients. It will then ask if they want another pizza. It will repeat this until they say no or they have six pizzas.
I don't really know how to explain my issues but I don't know how to loop the code so it asks for another pizza and each one has a different size and amount of toppings. I also don't know how I would print it.
Sorry if this is asking a lot or its confusing to understand or if the code is just painful to look at ahaha.
Thanks in advance.
CustomerName = input("Please input the customers name: ")
CustomerAddress = input("Please input the customers address: ")
CustomerNumber = input("Please input the customers number: ")
while True:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ")
try:
PizzaSize = str(PizzaSize)
if PizzaSize == "Small" or "Medium" or "Large":
break
else:
print("Size not recognized")
except:
print("Invalid input")
if PizzaSize == "Small":
SizeCost = 3.25
elif PizzaSize == "Medium":
SizeCost = 5.50
elif PizzaSize == "Large":
SizeCost = 7.15
print(SizeCost)
while True:
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
ExtraToppings = float(ExtraToppings)
if ExtraToppings >= 0 and ExtraToppings <= 4:
break
else:
print("Please insert a number over 0")
except:
print("Input not recognised")
if ExtraToppings == 1:
ToppingCost = 0.75
elif ExtraToppings == 2:
ToppingCost = 1.35
elif ExtraToppings == 3:
ToppingCost = 2.00
elif ExtraToppings >= 4:
ToppingCost = 2.50
else:
print("Number not recognized")
print(ToppingCost)
``

First of all, you should put the code from the second while loop in the first. There is no need for two while true loops. Then instead of
while True:
just put
pizza_count = 0 # how many pizzas they have
wantsAnotherPizza = True
while pizza_count < 6 and wantsAnotherPizza: # while they have less than 6 pizzas and they want another one
pizza_count += 1 # increase pizza_count as they order another pizza
# ... your code here from both of the while loops
x = input("Do you want another pizza? (Y/N)")
if x == "N" or x == "n":
global wantsAnotherPizza
wantsAnotherPizza = False:

You can modify your code like this. I thing you can simply your conditionals by using dictionaries. Try this
from collections import defaultdict
customer_order = defaultdict(list)
customer_order['CustomerName'] = input("Please input the customers name: ")
customer_order['CustomerAddress'] = input("Please input the customers address: ")
customer_order['CustomerNumber'] = input("Please input the customers number: ")
pizza_size ={
'small':3.25,
'medium': 5.50,
'large': 7.15
}
toppins= {'1': 0.75,
'2':1.35,
'3':2.00,
'4':2.50,
}
order = int(input("How many orders would you like to make: "))
while order:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ").lower()
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
if PizzaSize in pizza_size:
size_cost= pizza_size[PizzaSize]
if ExtraToppings:
ToppingCost= toppins[ExtraToppings]
else:
print("Number not recognized")
continue
customer_order['order'].extend([{'size':PizzaSize,'toppings': ToppingCost}])
order -= 1
else:
print("Size not recognized")
continue
except Exception as msg:
print("Invalid input", msg)
continue
else:
print('Your order is complete')
print(customer_order)

Related

Stuck at WHILE LOOP when pressing N for escaping from the loop

# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)

Global variable declaration error in Python

I am fairly new to Python/programming, I started about four months ago and since I am a teacher and may possible have a lot more time on my hands.
For my first project I have started to develop a pizza ordering system-- at the moment I am just having the user interact with the program through the terminal. However, I plan to evidentially use Django to create a web page so a user can actually interact with.
I will first share my code:
import re
sizePrice = {
'small': 9.69,
'large': 12.29,
'extra large': 13.79,
'party size': 26.49 }
toppingList = [ 'Anchovies', 'Bacon', 'Bell Peppers', 'Black Olives',
'Chicken', 'Ground Beef', 'Jalapenos', 'Mushrooms',
'Pepperoni','Pineapple', 'Spinach']
pickupCost = 0 deliveryCost = 5.0
running = True
def pick_or_delivery():
global delivery
print('\nWill this be for pick up or delivery?')
delivery = input("P - pick up / D - delivery")
delivery = delivery.title() # changes the letter inputted to an upper case.
print(f'This order will be for {delivery}')
if delivery == "D":
while running == True:
global customerName
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a vaild input")
else:
customerName = customerName.title()
break
while running == True:
global customerPhoneNumber
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
if not re.match("^[0-9 ]*$", customerPhoneNumber):
print("Please use numbers only")
elif len(customerPhoneNumber) == 0:
print("Please enter a a contact phone number")
else:
break
while running == True:
global streetName
streetName = input("Street name: ")
if not re.match("^[a-zA-Z ]*$", streetName):
print('Please use letters only.')
elif len(streetName) == 0:
print("Please enter a valid input")
else:
streetName = streetName.title()
break
elif delivery == "P":
while running == True:
global customerName
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a valid input")
else:
print("Please enter P or D")
customerName = customerName.title()
break
while running == True:
global customerPhoneNumber
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
customerName = customerName.title()
if not re.match("^[0-9 ]*$", customer_telephone):
print("Please use numbers only")
elif len(customer_telephone) == 0:
print("Please enter a valid input")
else:
break
else:
print("Please enter P or D ")
pick_or_delivery()
pick_or_delivery()
When I run this code I receive the following:
SyntaxError: name 'customerName' is used prior to global declaration
I know the issue is in my global variables, however in my code I am placing the global variable before it is being called. So I am a little confused. Is the placement incorrect? If so, where should it go?
I think it is because you have globalised customerName within your if statements. Try and create a variable called customerName at the start of your function and give it a blank value, then globalise it at the start of your function.

How can I save a variable for later use in a "While" loop?

I have a project for my Comp Sci class where I have to make an order form for a pizza restaurant. I am required to have the person select the size of the pizza, and the toppings wanted. I am trying to make a loop so that you can order multiple pizzas and multiple toppings per pizza. However, the way I currently have it, every time I re-run the loop to "order" another pizza, it resets the variables. Is there a way to do make it so I save the variable for later use when calculating the total price of the order? This project is in python, but we are technically using this site: https://www.jdoodle.com/python-programming-online/ because not everyone in the class is able to use the actual program since we are working online, and some people have chromebooks. It is mostly the same as the Python IDLE program, but requires you to type print more.
This is the main portion of the code:
while again == "y":
size = input("Select Size (Small = $8, Medium = $10, Large = $12. Select a Number 1-3: ")
print size
if size == 1:
pizzasize = 8
pizzaname = "Small"
if size == 2:
pizzasize = 10
pizzaname = "Medium"
if size == 3:
pizzasize = 12
pizzaname = "Large"
topprice = 0
print
again2 = "y"
while again2 == "y":
print ("Step 3: Select Toppings")
print
print ("Toppings: None, Extra Cheese, Pepperoni, Sausage, Bacon, Pineapple, Peppers")
topping = input("Select a Number 1-7: ")
print topping
if topping == 1:
topname = "None"
if topping == 2:
topname = "Extra Cheese"
if topping == 3:
topname = "Pepperoni"
if topping == 4:
topname = "Sausage"
if topping == 5:
topname = "Bacon"
if topping == 6:
topname = "Pineapple"
if topping == 7:
topname = "Peppers"
print ("Would You Like Another Topping?")
again2 = raw_input("Press Y/N: ")
print again2
print
topprice += 1.25
print topprice
print ("Would You Like To Order Another?")
again = raw_input("Press Y/N: ")
print again
if again == "y" and size ==1:
pizzasize += 8
if again == "y" and size ==2:
pizzasize += 10
if again == "y" and size ==3:
pizzasize += 12
print pizzasize
print

When I print my list instead of using the names in the list the output shows the index numbers. Python 2D-Lists

Here is my code the lists are where Im having issues. Im new to python and I do not understand how 2D-lists work but I need to add then in to the program for a grade. Any help will be appreciated.
#Define Vars
import locale
locale.setlocale( locale.LC_ALL, '')
order_total = 0.0
price = 3.5
fmt_price = locale.currency(price, grouping=True)
qty = int(0)
#cookie list
cookie_list = list()
cookie_list = "Savannah Thin-Mints Tag-a-longs Peanut-Butter Sandwich".split()
order_list = list()
#cookie choices
def disp_items():
print("Please choose one of our flavours. Enter the item number to choose")
for c in range(len(cookie_list)):
print("{}. \t{}".format(c+1, cookie_list[c]))
print()
#Menu Choices
def disp_menu():
choice_list = ["a", "d", "m", "q"]
while True:
print("\nWhat would you like to do?")
print("a = add an item")
print("d = delete an item")
print("m = display the meal so far")
print("q = quit")
choice = input("\nmake a selection: ")
if choice in choice_list:
return choice
else:
print("I dont't understand that entry. Please Try again.")
# Math Function**********************
def calc_tot(qty):
#this function is qty * price
return qty * 3.5
def disp_order():
print("\nGirl Scout Cookie Order for", cust)
print()
print("Itm\tName\tQty\tPrice")
print("---\t----\t----\t----")
order_total_items = 0 #accumulator
order_price = 0
for c in range(len(order_list)):
detail_list = [" ", 0]
detail_list.append(order_list)
print("{}.\t{}\t{}\t{}".format(c+1, order_list[c][0], order_list[c][1], price))
order_total_items += order_list[c][1]
order_price += price
print("\nYour Order Contains {} items for total of {} \n".format(order_total_items, order_price))
print("-" * 30)
#ADD Process
def add_process():
valid_data = False
while not valid_data:
disp_items()
try:
item = int(input("Enter item number: "))
if 1 <= item <= len(cookie_list):
valid_data = True
else:
print("\nThat was not a vaild choice, please try again.")
except Exception as detail:
print("error: ", detail)
#Valid Qty
valid_data = False
while not valid_data:
try:
qty = int(input("Enter Quantity: "))
if 1 <= qty <= 10:
valid_data = True
else:
print("\nThat was not a valid quantity, please try again.")
except Exception as detail:
print("Error; ", detail)
print("Please try again")
#Function call for multiplication
item_total = calc_tot(qty)
fmt_total = locale.currency(item_total, grouping=True)
#User Choice
print("\nYou choose: {} boxes of {} for a total of {}".format(qty,
cookie_list[item-1],
fmt_total))
print()
#verify inclusion of this item
valid_data = False
while not valid_data:
incl = input("Would you like to add this to your order? (y/n): ")
print()
if incl.lower() =="y":
#2-D List
inx = item - 1
detail_list = [inx, qty]
order_list.append(detail_list)
valid_data = True
print("{} was added to your order".format(cookie_list[inx]))
elif incl.lower() == "n":
print("{} was not added to your order".format(cookie_list[inx]))
valid_data = True
else:
print("That was not a vaild response, please try again")
#Delete function
def del_item():
if len(order_list) == 0:
print("\n** You have no items in your order to delete **\n")
else:
print("\nDelete an Item")
disp_order()
valid_data = False
while not valid_data:
try:
choice = int(input("Please enter the item number you would like to delete: "))
if 1<= choice <= len(order_list):
choice = choice - 1
print("\nItem {}. {} with {} boxes will be deleted".format(choice +1,
order_list[choice][0],
order_list[choice][1]))
del order_list[choice]
valid_data = True
except Exception as detail:
print("Error: ", detail)
print("Please try again")
#Main program
# Banner
print("Welcome to the Girl Scout Cookie")
print("Order Program")
cust = input("Please enter your name: ")
while True:
choice = disp_menu()
if choice == "a":
add_process()
elif choice == "d":
del_item()
elif choice == "q":
break
disp_order()
disp_order()
print("Thank you for your order")
Here's the output
Girl Scout Cookie Order for *****
Itm Name Qty Price
--- ---- ---- ----
1. **0** 1 3.5
2. **0** 1 3.5
3. **4** 5 3.5
Your Order Contains 7 items for total of 10.5
Under name there should be a name of a girl Scout Cookie and not the index number, how do i fix this?
Many Thanks.
When you print the order in disp_order() you should print from cookie_list[c] in the second column. And print the whole item instead off just the first letter.
print("{}.\t{}\t{}\t{}".format(c+1, cookie_list[c], order_list[c][1], price))
The cookie names are not of equal length, so you'll have to adjust for that.

Can't escape while loop

I am a beginning programmer writing in Python 3.5 for my Computer Concepts III class. This week we are working on data validation using try/except blocks and Boolean flags, modifying a program we made last week. I've almost completed my weekly assignment except for one thing. I can't figure out why I'm getting stuck in a while loop. This is the loop in question:
while not valid_data:
cont = input("Would you like to order another? (y/n) ")
if cont.lower not in yorn:
valid_data = False
else:
valid_data = True
yorn is ["y", "n"]
Here is the whole program for context:
# Program Lesson 6 Order
# Programmer Wiley J
# Date 2016.02.13
# Purpose The purpose of this program is to take an order for cookies.
# Import Class/Format Currency
import locale
locale.setlocale(locale.LC_ALL, '')
# Define Variables
boxes = 0
cost = 3.50
qty = 0
items = 0
yorn = ["y", "n"]
# Banner
print("Welcome to The Cookie Portal")
# Input
valid_data = False
while not valid_data:
name = input("Please enter your name: ")
if len(name) > 20:
print()
print("Not a valid name")
valid_data = False
elif len(name) == 0:
print("You need to enter a name")
valid_data = False
else:
print("Hello", name)
valid_data = True
cont = input("Would you like to place an order? (y/n) ")
# Process
while cont.lower() not in yorn:
cont = input("Would you like to place an order? (y/n) ")
while cont.lower() == "y":
valid_data = False
while not valid_data:
print("Please choose a flavor:")
print("1. Savannahs")
print("2. Thin Mints")
print("3. Tagalongs")
try:
flavor = int(input("> "))
if flavor in range (1, 4):
items += 1
valid_data = True
else:
valid_data = False
except Exception as detail:
print("Error", detail)
valid_data = False
while not valid_data:
try:
boxes = int(input("How many boxes? (1-10) "))
if boxes not in range (1, 11):
print("Please choose a number between 1 and 10")
valid_data = False
else:
qty += boxes
valid_data = True
except Exception as detail:
print("Error", detail)
print()
print("Please enter a number")
valid_data = False
while not valid_data:
cont = input("Would you like to order another? (y/n) ")
if cont.lower not in yorn:
valid_data = False
else:
valid_data = True
# Output
if cont.lower() == "n":
cost *= qty
print()
print("Order for", name)
print("-------------------")
print("Total Items = {}".format(items))
print("Total Boxes = {}".format(qty))
print("Total Cost = {}".format(locale.currency(cost)))
print()
print("Thank you for your order.")
I wouldn't be surprised if there are other issues with this code but they are most likely by design as per the requirements of the assignment. Any additional feedback is welcome.
It seems you are missing function-paranthesis in the end of "lower", like so:
if cont.lower() not in yorn:
Your problem is here:
if cont.lower not in yorn:
lower is a method, it should be:
if cont.lower() not in yorn:
In your code, you are doing cont.lower not in yorn. [some string].lower is a function, not a property, so you have to call it by putting parentheses after it.
cont = input("Would you like to order another? (y/n) ")
if cont.lower() not in yorn:
valid_data = False
else:
valid_data = True
You are missing a parentheses after .lower:
if cont.lower() not in yorn:

Categories