我怎么能循环涉及列表的代码

时间:2014-11-20 17:14:16

标签: python loops

我是python的新手,我想知道是否有人能够帮助我循环这段代码并且我在过去做了循环但是这个涉及一个列表元素,每次都要改变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 个答案:

答案 0 :(得分: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