为什么我的if / elif / else-code无效?

时间:2016-06-06 21:40:19

标签: python python-3.x if-statement

在python中,我试图让这段代码接受用户前进,如果他写“True”,而不是如果他为User_Answer中的语句写“False”。然而,当我运行代码时,我得到了“答案是正确的!” - 无论我写什么,都是一部分。我遇到问题的部分以“Test_Answer”开头。

有人可以帮我吗?

name_list = ["Dean", "Bill", "John"]
enter_club = ["Enter", "enter"]

print ("THE CLUB - by Mads")
print (" ")
print ("""You approach a secret club called \"The club\". The club members are dangerous.
Make sure you tell the guard one of the members names.""")
print ("")
print ("Good evening. Before you are allowed to enter, we need to check if your name is on our list.")

def enter_the_club():
    enter_now = input(" \nPress \"enter\" to enter the club... ")
    if (enter_now in enter_club) == True:
        print (" ")
        print ("But as you enter, you are met with an intelegence test. \n It reads:")

check_name = input("What is your name? ")               
def list_check():
    if (check_name in name_list) == True:
    print("Let me check.. Yes, here you are. Enjoy yourself, %s!" % check_name)
    enter_the_club()
elif check_name.isalpha() == False:
    print("Haha, nice try %s! Let's hear your real name." % check_name)
    list_check()
elif (check_name in name_list) == None:
    print ("You will need to give us your name if you want to come in.")
    list_check()
else:
    print ("I am sorry, but I can not find your name on the list, %s." % check_name)
    print ("Are you sure that's your listed name?")
    list_check()
list_check()

print ("But as you enter, you are met with an intelegence test.")
print (" ")
print ("It reads:")

Test_Answer = True

def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
    print ("Great, %s, the answer is correct!" % check_name)
else:
    print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
    IQtest()
 IQtest()

1 个答案:

答案 0 :(得分:0)

True是一个布尔常量。用户输入的内容将是&#34; True&#34;或者&#34; False&#34;,两个字符串。此外,您的 elif 条件不可能为真。你想用三个决策分支做什么?

不要太多改变你的代码......试试这个吗?

Test_Answer = "True"

def IQtest():
    User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
    if Test_Answer == User_Answer:
        print ("Great, %s, the answer is correct!" % check_name)
    else:
        print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
        IQtest()

请注意,我已经更正了您的&#34;否则&#34;语法。

此外,您对 check_name 没有任何价值;我认为这是一个你在其他地方处理的全局变量。