2014-11-20 82 views
-2

我對python相當陌生,我想知道是否有人能夠幫助我循環這段代碼,並且我在過去做了循環,但是這個循環包含一個list元素不得不每次改變1次到10次,我不知道如何做出改變。我該如何循環一個涉及列表的代碼

print ("Question 1: ") 
print (questions[0]) 
#asks for the answer from the user 
ans = int(input()) 
#compares the users input to the answer 
if ans == eval(questions[0]): 
    print ("Well done, you got it correct") 
    #if correct grants a point to the overall score 
    score = score + 1 

回答

1

這樣做,同時保持你的代碼最接近的方法如下

for index, question in enumerate(questions): 
    print ("Question {}: ".format(index+1)) 
    print (question) 
    #asks for the answer from the user 
    ans = int(input()) 
    #compares the users input to the answer 
    if ans == eval(question): 
     print ("Well done, you got it correct") 
     #if correct grants a point to the overall score 
     score = score + 1 

請注意,您應該避免使用eval,因爲它是不安全的。推薦的替代方案是製作包含預先回答的問題和答案的詞典,例如

questions = {'What is 5 + 4?' : 9, 
      'What is 3 - 1?' : 2} 

programmatically come up with questions and answers

+0

「不安全」是什麼意思? – 2014-11-20 17:28:43

+0

請參閱[這裏](http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice)例如,也[這裏](http://nedbatchelder.com /blog/201206/eval_really_is_dangerous.html)。 – CoryKramer 2014-11-20 17:29:28

+0

但如果我使用它爲一個簡單的程序,不是太複雜,我應該沒事吧?或者在可能嘗試擴展時遇到問題? – 2014-11-20 17:32:44

相關問題