问题描述
我想这样做,但我评论了 3 个问题:
age = input("How old are you ? ")
if type(age) != int: # this line does't work
restart = input("invalid input. Do you want to restart ? [y/n]")
if restart == "y" :
#restart the program
else :
#exit the program
解决方法
使用 try-except 块检查输入 (str
) 到 int
的转换
age = input("How old are you ? ")
try:
age = int(age)
except ValueError:
restart = input("invalid input. Do you want to restart ? [y/n]")
if restart == "y" :
#restart the program
else :
#exit the program