[英]How do I use input from user to close or continue a while loop
我正在尝试制作一个解决此问题的程序。 如果用户想订购更多,我似乎无法得到部分,他说是,然后循环继续。
首先要求用户在 3 种不同类型的比萨饼之间进行选择(margherita:15.5SGD,marinara:17.5SGD 和 napoletana:18SGD)。 一旦选择了比萨饼类型,他就被邀请输入他想订购的这种比萨饼的数量。
最后,询问用户是否愿意停止订购。 如果不是,则菜单返回再次询问 select 披萨类型。 如果是,则根据订购的比萨饼打印最终价格,程序停止。
这是我到目前为止得到的
margherita_P= 15.5
marinara_P= 17.5
napoletana_P= 18
Pizza_Option = input("key in type of pizza wanted: ")
Pizza_Amt = int(input("amt of pizza wanted: "))
x = 1
price = 0
while x == 1:
if Pizza_Option == 'margherita':
price += margherita_P * Pizza_Amt
print(price, " SGD")
elif Pizza_Option == 'marinara':
price += marinara_P * Pizza_Amt
print(price, " SGD")
elif Pizza_Option == 'napoletana':
price += napoletana_P * Pizza_Amt
print(price, " SGD")
else:
print("error")
y= input("type yes if you want more: ")
if y != 'yes':
x +=1
目前,您处于无限循环中,因为您要退出的行实际上并不在循环中。 这些行必须缩进。 此外,您必须将类型和数量的输入放入循环中。
margherita_P = 15.5
marinara_P = 17.5
napoletana_P = 18
x = 1
price = 0
while x == 1:
Pizza_Option = input("key in type of pizza wanted: ")
Pizza_Amt = int(input("amt of pizza wanted: "))
if Pizza_Option == 'margherita':
price += margherita_P * Pizza_Amt
print(price, " SGD")
elif Pizza_Option == 'marinara':
price += marinara_P * Pizza_Amt
print(price, " SGD")
elif Pizza_Option == 'napoletana':
price += napoletana_P * Pizza_Amt
print(price, " SGD")
else:
print("error")
y = input("type yes if you want more: ")
if y != 'yes':
x += 1
您可以将用户输入部分包装到while
循环中,并在用户拒绝时退出循环。 这是我的建议:
margherita_P = 15.5
marinara_P = 17.5
napoletana_P = 18
total_price = 0
while True:
Pizza_Option = input("key in type of pizza wanted: ")
Pizza_Amt = int(input("amt of pizza wanted: "))
if Pizza_Option == 'margherita':
price = margherita_P * Pizza_Amt
total_price += price
print(price, " SGD")
elif Pizza_Option == 'marinara':
price = marinara_P * Pizza_Amt
total_price += price
print(price, " SGD")
elif Pizza_Option == 'napoletana':
price = napoletana_P * Pizza_Amt
total_price += price
print(price, " SGD")
else:
print("error")
y = input("type yes if you want more: ")
if y != 'yes':
break
print("Total price: ", total_price)
Output:
key in type of pizza wanted: margherita
amt of pizza wanted: 3
46.5 SGD
type yes if you want more: yes
key in type of pizza wanted: napoletana
amt of pizza wanted: 5
90 SGD
type yes if you want more: no
Total price: 136.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.