Skip to main content
 首页 » 编程设计

python之如何通过 Python 中的 input() 函数为无法转换为整数的字符串提供无效消息

2025年05月04日47dyllove98

我正在尝试编写一个程序,根据用户对“你的高度是多少?”这个问题的回答向用户发出响应。

我在第 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") 

示例 session :

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