等于不等于

时间:2013-02-18 21:31:08

标签: python equals

无法让python测验程序工作,当'useranswer'为'correctanswer'时,如果循环不能正常工作,并表明即使它们不相同也不相同。我想知道这是否存在比较列表中保存的字符串的问题,但我真的不知道如何解决它。任何帮助将不胜感激。

谢谢

import sys

print ("Game started")
questions = ["What does RAD stand for?",
            "Why is RAD faster than other development methods?",
            "Name one of the 3 requirements for a user friendly system",
            "What is an efficient design?",
            "What is the definition of a validation method?"]


answers = ["A - Random Applications Development, B - Recently Available Diskspace, C - Rapid Applications Development",
            "A - Prototyping is faster than creating a finished product, B - Through the use of CASE tools, C - As end user evaluates before the dev team",
            "A - Efficient design, B - Intonated design, C - Aesthetic design",
            "A - One which makes best use of available facilities, B - One which allows the user to input data accurately, C - One which the end user is comfortable with",
            "A - A rejection of data which occurs because input breaks predetermined criteria, B - A double entry of data to ensure it is accurate, C - An adaption to cope with a change external to the system"]

correctanswers = ["C", "B", "A", "A", "A"]
score = 0
lives = 4
z = 0

for i in range(len(questions)):
    if lives > 0:
        print (questions[z])
        print (answers[z])
        useranswer = (input("Please enter the correct answer's letter here: "))
        correctanswer = correctanswers[z]
        if (useranswer) is (correctanswer):     //line im guessing the problem occurs on
            print("Correct, well done!")
            score = score + 1
        else:
            print("Incorrect, sorry. The correct answer was;  " + correctanswer)
            lives = lives - 1
            print("You have, " + str(lives) + " lives remaining")
        z = z + 1
    else:
        print("End of game, no lives remaining")
        sys.exit()

print("Well done, you scored" + int(score) + "//" + int(len(questions)))

3 个答案:

答案 0 :(得分:8)

您应该使用==进行比较:

if useranswer == correctanswer: 

is运算符执行身份比较。并且==>,运算符执行值比较,这就是您所需要的。


对于两个对象obj1obj2

obj1 is obj2  iff id(obj1) == id(obj2)  # iff means `if and only if`.

答案 1 :(得分:7)

运算符isis not测试对象标识x is y true 当且仅当 xy 是同一个对象。而运营商<>==>=<=!=会比较两个对象。

...因此

    if (useranswer) is (correctanswer):     //line im guessing the problem occurs on

应该......

    if useranswer == correctanswer:

由于您要检查用户的回答是否匹配正确答案。它们在记忆中不是同一个物体。

答案 2 :(得分:1)

is运算符测试对象标识。检查docs。我希望this SO thread也可能有所帮助。