python - 让用户输入采用字符串和整数?(Python)
问题描述
prompt = "Enter your age for ticket price"
prompt += "\nEnter quit to exit: "
active = True
while active:
age = input(prompt)
age = int(age)
if age == 'quit':
active = False
elif age < 3:
print("Your ticket is $5")
elif age >= 3 and age < 12:
print("Your ticket is $10")
elif age >= 12:
print("Your ticket is $15")
这是一些相当简单的代码,但我遇到了一个问题。问题是,要运行代码,必须将年龄转换为 int。但是,当您输入“退出”时,程序也应该退出。你总是可以有另一个提示“你想添加更多的人吗?”。但是,有没有办法让它运行而不必提示另一个问题?
解决方案
我建议去掉该active
标志,并在break
输入时"quit"
输入,就像这样,然后您可以安全地转换为int
,因为如果输入代码将不会到达该点"quit"
:
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is $5")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
请注意,age >= 3
andage >= 12
检查是不必要的,因为您已经用早期的检查保证了它们。
推荐阅读
- git - 我需要一种 100% 确定的方法来使我的 GitHub 分叉和克隆与原始版本相同吗?
- mysql - 在 mySQL 中运行的奇怪正则表达式
- python-3.x - 从引发错误的同一点继续执行脚本
- .net - [MsTeams][BotFrameworkV4][Adaptive Card ] 团队中可滚动的自适应卡片
- regex - 如何通过 TYPO3 的重定向模块重定向以特定路径开头的 URL?
- android - 处理程序 - PostDelayed 方法“破坏”其余(块)代码?
- javascript - 如何将图表输入值格式,而不是百分比格式
- r - 如何在 R 函数中操作变量名称?
- tensorflow - 张量板数据
- mysql - 带有损坏子查询的 Sql 查询返回结果