如何在python中修复if,elif,else语句?

时间:2014-10-27 17:51:38

标签: python if-statement

我正在为一个有趣的omegle模拟器工作,它询问你的年龄,如果你已经足够老,问你是否有kik。如果你的年龄是16或更高,它可以正常工作,但如果你说不到这个,它会出现错误。这是代码:

age = input("age?\n")
if age == "1":
    print ("Too young bby")
elif age == "2":
    print ("Too young bby")
elif age == "3":
    print ("Too young bby")
elif age == "4":
    print ("Too young bby")
elif age == "5":
    print ("Too young bby")
elif age == "6":
    print ("Too young bby")
elif age == "7":
    print ("Too young bby")
elif age == "8":
    print ("Too young bby")
elif age == "9":
    print ("Too young bby")
elif age == "10":
    print ("Too young bby")
elif age == "11":
    print ("Too young bby")
elif age == "12":
    print ("Too young bby")
elif age == "13":
    print ("Too young bby")
elif age == "14":
    print ("Too young bby")
elif age == "15":
    print ("Too young bby")
else:
    kik = input("Do you have kik?\n")
yes = "yes"
if kik == yes:
    print ("add me bby")
else:
    print ("bye")

出现的错误是:

 Traceback (most recent call last):
  File "C:/Users/Public/Documents/python/omegle.py", line 36, in <module>
    if kik == yes:
 NameError: name 'kik' is not defined

有谁知道如何修复它?

5 个答案:

答案 0 :(得分:2)

你应该在这里解决几件事。首先,使用int()

将年龄存储为数字
age = int(input("age?\n"))

然后做一个小于:

if(age < 16):
  print ("Too young bby")
else:
  kik = input("Do you have kik?\n")
  if kik == "yes":
    print ("add me bby")
  else:
    print ("bye")

答案 1 :(得分:2)

问题是你只在这个区块中设置kik

else:
    kik = input("Do you have kik?\n")

如果未到达此块,则kik不存在。一个选项是在if / elif块之前设置它。


此外,你可以缩短它:

kik = "no"
age = input("age?\n")
if int(age) < 16:
    print ("Too young bby")
else:
    kik = input("Do you have kik?\n")
yes = "yes"
if kik == yes:
    print ("add me bby")
else:
    print ("bye")

答案 2 :(得分:1)

kik设置为默认值,它应该在链外。

age = input("age?\n")
kik = "no" #assuming no is default
...

与您的代码一样,只有在您点击else

时才会定义

答案 3 :(得分:1)

简短的回答是kik超出范围,将kik = "no"放在程序的开头应该可以消除该错误。

但是,这是完成整个事情的更好方法:

age = int(input("age?\n"))
kik = "no"

if age < 16:
    print ("Too young bby")
else:
    kik = input("Do you have kik?\n")

if kik == yes:
    print ("add me bby")
else:
    print ("bye")

答案 4 :(得分:0)

安迪的帖子对我很有帮助。我要补充一件事。如果在第一个问题中输入小于16的整数,则将同时显示打印(“ Too young bby”)和“打印”(再见)。第一个输出仅够我使用,不能打印(“再见”)。 为此,您可以将第二个“ if”语句缩进第一个“ else”语句。 如果您不缩进我的代码,则会得到“您没有资格在爱尔兰投票”。两次。这是我的例子;

Citizen = "No"
Yes = "Yes"
Age = int(input("What is your age?: \n"))
if (Age) < 18:
    print("You are not eligible to vote in Ireland.\n")
else:
    Citizen = input("Do you hold Irish Citizenship? Yes/No: \n")
    if Citizen == Yes:
        print("You are eligible to vote in Ireland.\n")
    else:
        print("You are not eligible to vote in Ireland.\n")