python - Python3:如何获得用户的重复响应并再次运行循环
问题描述
首先,我真的很抱歉提出这样一个微不足道的问题。我对编程完全陌生。我正在尝试学习一些 Python。我正在关注的书是“ Python Crash Course - 2nd Edition ”。我希望你和我裸露。我试图解决一个问题。问题如下,
电影院根据一个人的年龄收取不同的票价。3岁以下的人,门票免费;如果他们在 3 到 12 岁之间,则票价为 10 美元;如果他们超过 12 岁,票价为 15 美元。编写一个循环,询问用户的年龄,然后告诉他们电影票的价格。
我的目标
其实我解决了这个问题。当用户输入不是 int 时,我还设法通过使用 isdigit() 方法进行了一些错误处理,这在问题中没有被问到。现在我正在尝试实现类似我的程序应该要求用户进行第二次响应的东西。如果用户说是,我的循环应该再次运行,如果不是,它应该结束。我真的很抱歉弄了这么久。我只是想尽可能清楚。提前致谢!
注释块是我尝试过的。
编码:
print ("**********Welcome to Super Cinemas**********")
prompt = ("Enter your age to check for ticket price. ")
prompt += ("Enter 'exit' to quit. " )
age = input (prompt)
while age != 'exit':
if age.isdigit() != True:
print("Invalid input, please try again..")
age = input (prompt)
elif age.isdigit() == True:
age = int (age)
if age < 3:
print ("Voila, your tickets are free!")
break
elif age >= 3 and age <= 12:
print ("The cost of the ticket is $10")
break
elif age >= 13 and age <= 90:
print ("The cost of the ticket is $15")
break
else:
print ("Sorry, exceeding age limits..")
break
# repeat = input ("Do you wanna check more? y/n ")
# if repeat == 'y':
# continue
# else:
# break
解决方案
首先,您有一个获取年龄并给出结果的循环,因此获取年龄应该在 while 循环内。
您的年龄验证错误,假设您没有输入正确的年龄(非数字)并且程序要求另一个,但它会要求在之后继续循环而不是给出结果,这可以通过使用 continue 而不是得到另一个年龄。
如果您没有break
and continue
,您的 while 循环将继续直到输入 end .
您不需要处理年龄的 if 语句中的 break 语句,如果其中任何一个被执行,则不会检查其他语句。你为什么使用它们?
如果你得到'y',循环会自动继续,所以你不需要显式地放置 continue 语句。
您可以简化一些表达式:
age >= 13 and age <= 90
至3 <= age <= 12
和
if age.isdigit() != True
至if not age.isdigit()
代码
while True:
age = input(prompt)
if age.isdigit() != True:
print("Invalid input, please try again..")
continue
elif age.isdigit() == True:
age = int(age)
if age < 3:
print("Voila, your tickets are free!")
elif age >= 3 and age <= 12:
print("The cost of the ticket is $10")
elif age >= 13 and age <= 90:
print("The cost of the ticket is $15")
else:
print("Sorry, exceeding age limits..")
repeat = input("Do you wanna check more? y/n ")
if repeat != 'y':
break
推荐阅读
- php - 用户必须使用内置于 MustEmailVerify 的 laravel 注册后如何发送注册电子邮件
- azure-functions - local.settings.json 的自定义部分中的 EventHubTrigger 参数
- r - R - 找不到函数“cld”
- python - Django 模型 *** IndexError:列表索引超出范围
- python - 如何将 python 连接到 IBM DB2?
- c# - 如何取消 PreviewKeyDown 事件中的关键操作
- php - wordpress preg_match_all() 错误,使用 preg_replace_callback
- python - 按照视频教程进行操作,但出现很多错误
- javascript - PubNub 订阅不断取消订阅
- asp.net-core - 如何在 Openshift 容器中设置 ASP.NET Core 端口