2013-02-18 145 views
3

當'useranswer'爲'correctanswer'時,如果循環無法正常工作並且即使它們處於不正常狀態,也不能使Python測驗程序正常工作。我想知道這是否是比較字符串保存在列表中的問題,但我真的堅持要做什麼來解決它。任何幫助將非常感激。等於不等於

謝謝

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

您可以通過接受小寫字母並忽略空白列表來讓用戶更加靈活。 'if useranswer.strip()。upper()== correctanswer:' – 2013-02-18 21:50:57

回答

7

運營商is對象標識is not測試:x is ytrue當且僅當xy是同一個對象。而運營商<,>, ==,>=,<=!=比較兩個對象的

因此...

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

應該是...

if useranswer == correctanswer: 

由於要檢查是否有用戶的答案比賽正確的答案。他們不是內存中的同一個對象。

+0

謝謝,並且很好地解釋了 – user2075419 2013-02-18 21:46:38

+0

@ user2075419:高興地幫忙。 – Johnsyweb 2013-02-18 22:17:13

8

您應該使用==比較:

if useranswer == correctanswer: 

is符不身份比較。而==,>,運營商做價值比較,這就是你需要的。


對於兩個對象,obj1obj2

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

非常感謝! – user2075419 2013-02-18 21:39:24

+0

@ user2075419。不客氣:) – 2013-02-18 21:40:07

1

is操作者的測試對象的身份。檢查docs。我希望this SO thread也可能有幫助。

+0

謝謝你,爲什麼我從來沒有找到像這樣的線程當我看... – user2075419 2013-02-18 21:47:23