2014-11-20 38 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

相关问题