我试图编写一个程序,根据用户对“您的身高是多少?”这个问题的响应,向他/她发出响应。
我遇到了第4-7行的问题,在第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")任何帮助/建议都是非常感谢的!
发布于 2017-01-04 03:05:51
处理异常并重复,直到得到一个有效的数字:
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发布于 2017-01-04 03:08:26
如果用户输入一个无效的数字,那么您的程序将在第1行上立即崩溃,并带有值错误。
我建议的是在输入周围设置一个try/语句。
height = 0
while True: # Will keep looping until correct input is given
try:
height = int(input("What is your height?"))
break
except ValueError:
print("Please enter a valid number")
#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")https://stackoverflow.com/questions/41455570
复制相似问题