等于不等于

3
无法使python测验程序正常运行,当'useranswer'等于'correctanswer'时,if循环不能正常工作,并且即使它们相等,它也会声明它们不相等。我想知道这是否是与保存在列表中的字符串进行比较的问题,但我真的不知道该怎么做才能修复它。非常感谢任何帮助。

谢谢

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

1
通过接受小写字母并忽略空格,可以使用户更加灵活。如果useranswer.strip().upper() == correctanswer: - John La Rooy
3个回答

8

在比较时应该使用==

if useranswer == correctanswer: 

is运算符进行身份比较。 而==>运算符进行值比较,这正是您所需要的。


对于两个对象obj1obj2

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

7
运算符isis not用于测试对象标识:当且仅当xy是同一个对象时,x is y的结果为true。而运算符<>==>=<=!=则比较两个对象的
因此...
    if (useranswer) is (correctanswer):     //line im guessing the problem occurs on

应该是...

    if useranswer == correctanswer:

由于您想检查用户的答案是否匹配正确答案。它们在内存中不是相同的对象。


谢谢,讲解得非常清楚。 - user2075419

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接