gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:45:02 25 4
gpt4 key购买 nike

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

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

关于python - 如何通过 Python 中的 input() 函数为无法转换为整数的字符串提供无效消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41455570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com