首页 > 解决方案 > 代码中的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 作为我的年龄,它仍然继续并打印“欢迎”而不是“你不够老”

标签: pythonpython-2.7

解决方案


@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")

推荐阅读