代码中的elif函数错误

时间:2018-06-24 07:03:44

标签: python python-2.7

我是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作为年龄,它也会继续显示并打印“ Welcome”(欢迎)而不是“您还不够大”

1 个答案:

答案 0 :(得分:1)

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