-2

I'm fairly new to python and I was wondering if someone was able to help me with looping this block of code and I did looping in the past but this one involves a list element having to change every time 1 through to 10 and I don't know how I could make that change.

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
Brad Larson
  • 170,088
  • 45
  • 397
  • 571

1 Answers1

1

The closest way to do so while maintaining your code is the following

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

Note that you should avoid using eval because it is unsafe. Recommended alternatives are to either make a dictionary with pre-baked questions and answers, e.g.

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

Or programmatically come up with questions and answers.

Community
  • 1
  • 1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • what do you mean by 'unsafe' ? – New Python User Nov 20 '14 at 17:28
  • See [here](http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice) for example, and also [here](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html). – Cory Kramer Nov 20 '14 at 17:29
  • but if i use it for a simple program that isn't too complicated i should be fine right ? or will I encounter a problem when possibly trying to expand it? – New Python User Nov 20 '14 at 17:32
  • For your example, yes you will be fine, unless the question contains invalid syntax, which will just result in an error. In professional software development, people should rarely (if ever) use `eval`. – Cory Kramer Nov 20 '14 at 17:34
  • this is just for school work so no worries, greatly appreciate your help. – New Python User Nov 20 '14 at 17:42