我正在尝试创建一个用户可以在程序结束时停止的循环。我已经尝试了各种解决方案,其中没有一个有效,我设法做的就是创建循环,但我似乎无法结束它。我最近才开始学习Python,如果有人能在这个问题上给我启发,我将不胜感激。
def main():
while True:
NoChild = int(0)
NoAdult = int(0)
NoDays = int(0)
AdultCost = int(0)
ChildCost = int(0)
FinalCost = int(0)
print ("Welcome to Superslides!")
print ("The theme park with the biggest water slide in Europe.")
NoAdult = int(raw_input("How many adults are there?"))
NoChild = int(raw_input("How many children are there?"))
NoDays = int(raw_input("How many days will you be at the theme park?"))
WeekDay = (raw_input("Will you be attending the park on a weekday? (Yes/No)"))
if WeekDay == "Yes":
AdultCost = NoAdult * 5
elif WeekDay == "No":
AdultCost = NoAdult * 10
ChildCost = NoChild * 5
FinalCost = (AdultCost + ChildCost)*NoDays
print ("Order Summary")
print("Number of Adults: ",NoAdult,"Cost: ",AdultCost)
print("Number of Children: ",NoChild,"Cost: ",ChildCost)
print("Your final total is:",FinalCost)
print("Have a nice day at SuperSlides!")
again = raw_input("Would you like to process another customer? (Yes/No)")
if again =="No":
print("Goodbye!")
return
elif again =="Yes":
print("Next Customer.")
else:
print("You should enter either Yes or No.")
if __name__=="__main__":
main()
答案 0 :(得分:0)
您可以将返回更改为中断并退出while循环
if again =="No":
print("Goodbye!")
break
答案 1 :(得分:0)
而不是:
while True:
你应该用这个:
again = True
while again:
...
usrIn = raw_input("Would you like to process another customer? y/n")
if usrIn == 'y':
again = True
else
again = False
我只是默认为False,但如果他们没有输入y或n,你总是可以让用户要求输入新的输入。
答案 2 :(得分:0)
我使用python 3.5检查了你的代码,在我将raw_input
更改为input
之后它运行了,因为3.5中的输入是raw_input 2.7。由于您将print()用作函数,因此您应该在导入部分中从将来的包中导入print函数。我在脚本中看不到导入部分。
究竟什么不起作用?
此外:通过退出代码而不是破坏和结束来结束命令行应用程序是一个好习惯。所以你必须
import sys
在python脚本的导入部分中,当用户检查程序结束时,请执行
if again == "No":
print("Good Bye")
sys.exit(0)
这使您有机会在出现错误时退出并使用不同的退出代码。
答案 3 :(得分:0)
更改此代码段
60