【问题标题】:how could write a program to get age as an input?如何编写程序以获取年龄作为输入?
【发布时间】:2021-03-18 14:50:43
【问题描述】:

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

【问题讨论】:

标签: python input exit restart invalid-characters


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多