python - 代码中的elif函数错误
问题描述
我是 Python 的新手,正在尝试构建一个基于文本的游戏。第一个问题是“你几岁?”
当用户不输入年龄时,如何使用 if/else 语句打印特定消息。
例如,如果用户输入一个字符而不是一个字母,我想打印“请输入一个数字,而不是字符”,或者如果用户输入一个小于 12 的数字,我想打印“你不够老”,如果用户输入一个大于或等于 12 的数字 我想说“欢迎”
我已经编写了一些代码来尝试自己执行此操作并花了大约 4 个小时但无法弄清楚。
这是我的代码块:
input_age = raw_input("What is your age, " + input_name + "? ")
if len(input_age) == 0:
print("You didn't enter anything")
elif input_age < 12 and input_age.isdigit():
print("Sorry, you are not old enogh to play")
elif input_age >= 12 and input_age.isdigit():
print ("Welcome")
else:
print("You entered a character or characters instead of a digit or digits")
出于某种原因,第 4 行上的 elif 被跳过或其他原因,因为即使我输入 4 作为我的年龄,它仍然继续并打印“欢迎”而不是“你不够老”
解决方案
@roganjosh 是对的,raw_input
返回一个字符串,所以你必须执行以下操作:
input_age = raw_input("What is your age, " + input_name + "? ")
if not input_age:
print("You didn't enter anything")
elif input_age.isdigit():
if int(input_age) < 12 :
print("Sorry, you are not old enogh to play")
elif int(input_age) >= 12:
print ("Welcome")
if not input_age.isdigit():
print("You entered a character or characters instead of a digit or digits")
推荐阅读
- javascript - HighCharts 数据结构 - 多个独立系列,堆积柱形图
- sql-server - SQL Server 是否存储最初创建用户定义函数的用户的名称?
- python - 选择一个选项后添加带有 n-1 个选项的连续下拉菜单
- bash - 从脚本中的 ftp 链接下载基因组序列时的 BASH 变量解释
- c# - 为什么此 ASP.NET Core POST 请求返回“405(不允许方法)”?
- wpf - 使用 Resources.BeginInit() 更新 ResourceDictionary
- google-app-engine - 在本地开发服务器上使用 get_serving_url() 提供图像时出现问题
- java - SQS Java lambda获取空对象
- arrays - R,从矩阵和向量控制数组的数量
- javascript - ArangoDB + JSON + Vue 命名法:如果到处使用 kebab-case 会遇到什么问题?