如何编写程序以获取年龄作为输入?

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...