如何用不同的结果循环相同的变量



嗨,我有一个学校项目,要求我编写一个程序,询问用户的详细信息,然后询问他们想要什么尺寸的披萨和多少配料。然后它会问他们是否想要另一个披萨。它会重复这个过程,直到他们说不,或者他们有六个披萨。

我真的不知道如何解释我的问题,但我不知道如何循环代码,所以它要求另一个披萨,每个披萨都有不同的尺寸和数量的浇头。我也不知道该怎么打印。如果这是一个很大的问题,或者理解起来很困惑,或者代码看起来很痛苦,我很抱歉。

提前谢谢。

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

首先,您应该将第二个while循环中的代码放在第一个循环中。不需要两个while true循环。然后代替

while True:

只需放入

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:

您可以这样修改代码。我想你可以用字典来简化条件句。试试这个

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)

最新更新