python - 如何编写程序以获取年龄作为输入?
问题描述
我想这样做,但我评论时遇到了 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
推荐阅读
- php - 选择 * 其中 Column_A 和 Column_B 是唯一的
- python - 编写一个程序,生成 20 次随机掷骰子序列并打印骰子值,只标记最长的一次
- python - 如何在进程启动时缓存字典值
- windows - 应用程序无法在 Windows 7 上正确启动 (0xc000007b) 错误。旧版本仍然可以正常工作
- python - 如何将变量插入字符串?
- python - 熊猫数据框比较索引的所有列值而没有列名参考
- python - 我每次都需要为新变量分配可能无限数量的值
- visual-studio - 如何确认 Eigen 在 Visual Studios 中启用矢量化?如何检查是否定义了 EIGEN_VECTORIZE 预处理器符号?
- html - 折叠表格行而不是单元格时是否存在已知问题?
- python - Python 3:使用 Exec 赋值