嵌套while循环逻辑异常排查:电影票价程序退出问题
电影票价计算程序的循环逻辑问题
我正在练习while循环及通用循环编程技巧,遇到了一个问题。我尝试编写一个根据用户年龄计算电影票价的程序:外层循环和第一个输入语句处理年龄转票价的逻辑。用户输入年龄并得到对应票价后,外层循环中的内层循环会通过第二个输入询问是否有其他同行人员,预期逻辑如下:
- 若用户回答'no',整个程序终止
- 若回答'yes',仅内层循环终止,外层循环重新执行
- 若输入非'yes'/'no',内层循环重新执行
但实际运行时,在内层循环输入'no'时,仅内层循环终止,外层循环会重新启动,无法实现整个程序退出的预期效果。
初始代码
while True: age = input("Enter your age and the price of the movie will be displayed: ") if age == 'quit': break elif int(age) < 3: print("You're ticket price today is free.") elif int(age) < 12: print("You're ticket price today is $10. ") elif int(age) <= 150: print("You're ticket price today is $15") elif int(age) > 150: print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.") else: print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.") while True: repeat = input("Do you have someone else who's attending this movie? (yes/no): ") if repeat.lower() == 'no': break elif repeat.lower() == 'yes': break else: print("You've entered an invalid input. Please enter 'yes' to add someone or 'no' to quit.")
优化尝试代码(更新2)
flag = True while flag: while True: age = input("Enter your age and the price of the movie will be displayed: ") if age == 'quit': break elif int(age) < 3: print("You're ticket price today is free.") elif int(age) < 12: print("You're ticket price today is $10. ") elif int(age) <= 150: print("You're ticket price today is $15") elif int(age) > 150: print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.") else: print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.") while True: repeat = input("Do you have someone else who's attending this movie? (yes/no): ") if repeat.lower() == 'no': flag = False break elif repeat.lower() == 'yes': break else: print("You've entered an invalid input. Please enter 'yes' to add someone or 'no' to quit.")
内容的提问来源于stack exchange,提问作者EM284
相关产品推荐
相关产品推荐

