无法转换为整数的字符串

无法转换为整数的字符串

我正在尝试编写一个程序,该程序根据用户对“您的身高是多少”的回答,向用户发出响应。

我在第4-7行遇到麻烦,我试图让用户输入有效的提示(即,防止收到无法转换为整数的字符串)。

我的代码在这里:

#ask for user's height, and convert reply into an integer
height = int(input("What is your height?"))

#check if user's input can be converted to an integer
if type(height) != int:
    print("Please enter a valid number")
    height = int(input("What is your height?")

#give user a response, based on user's height
if height > 180:
    print("Your height, " + str(height) + ", is above average")
elif height > 155:
    print("Your height, " + str(height) + ", is average")
else:
    print("Your height, " + str(height) + ", is below average")


任何帮助/建议都非常感谢!

最佳答案

处理异常并重复直到获得有效数字:

while True:
    try:
        height = int(input("What is your height? "))
        break
    except ValueError:
        print("Please enter a valid number")

if height > 180:
    print("Your height, " + str(height) + ", is above average")
elif height > 155:
    print("Your height, " + str(height) + ", is average")
else:
    print("Your height, " + str(height) + ", is below average")


会话示例:

What is your height?: abc
Please enter a valid number
What is your height?: xyz
Please enter a valid number
What is your height?: 180
Your height, 180, is average

10-05 18:45