如何在Python中接受int转换的字符串字母输入?
我正在做一个简单的 python 练习,我会提出一系列问题并从用户那里获取输入。我提示用户“输入你的年龄”,如果用户输入年龄的字母值而不是 int,我希望程序继续而不是损坏,因为如果年龄小于 18 或,我将转换为 int 来计算数字大于且如果在特定年龄之间。我无法将字母转换为整数。
age = input("Please enter your age: ")
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
#Somewhere in this script I am hoping to accept the letter input without sending an error to the program.
I am working on a simple python exercise where I ask a series of questions and get input from the user. I prompt the user with "Enter your age" and I want the program to continue rather than be corrupt if the user enters a letter value for the age rather than int because I am converting to int to figure if the age is less than 18 or greater than and if it is between specific ages. I can't convert letters to an int.
age = input("Please enter your age: ")
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
#Somewhere in this script I am hoping to accept the letter input without sending an error to the program.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用尝试/例外。
如果你的 int 转换失败,代码将跳转到 except 而不是崩溃。
如果您希望用户重试,您可以编写类似的内容。请注意您使用的范围和负数。
Use try/except.
If your int conversion fails the code will jump to except instead of crashing.
If you want the user to retry, you could write something like this instead. Be aware of the ranges you're using and negative numbers.
我会使用 while 循环,例如
正如@Barmar 所说,您需要检查您的 if 语句。
I'd use a while loop, e.g.
And as @Barmar stated, you need to check your if statements.