首页 > 解决方案 > 如何编写程序以获取年龄作为输入?

问题描述

我想这样做,但我评论时遇到了 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

标签: pythoninputexitrestartinvalid-characters

解决方案


使用 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

推荐阅读