I am having trouble understanding why some variables are local and some are global. For instance. when i try this:
from random import randint score = 0 choice_index_map = {"a": 0, "b": 1, "c": 2, "d": 3} questions = [ "What is the answer for this sample question?", "Answers where 1 is a, 2 is b, etc.", "Another sample question; answer is d." ] choices = [ ["a) choice 1", "b) choice 2", "c) choice 3", "d) choice 4"], ["a) choice 1", "b) choice 2", "c) choice 3", "d) choice 4"], ["a) choice 1", "b) choice 2", "c) choice 3", "d) choice 4"] ] answers = [ "a", "b", "d" ] assert len(questions) == len(choices), "You haven't properly set up your question-choices." assert len(questions) == len(answers), "You haven't properly set up your question-answers." def askQ(): # global score # while score < 3: question = randint(0, len(questions) - 1) print questions[question] for i in xrange(0, 4): print choices[question][i] response = raw_input("> ") if response == answers[question]: score += 1 print "That correct, the answer is %s." % choices[question][choice_index_map[response]] # eg choices[1][2] else: score -= 1 print "No, I'm sorry -- the answer is %s." % choices[question][choice_index_map[answers[question]]] print score askQ()
I get this error:
Macintosh-346:gameAttempt Prasanna$ python qex.py Answers where 1 is a, 2 is b, etc. a) choice 1 b) choice 2 c) choice 3 d) choice 4 > b Traceback (most recent call last): File "qex.py", line 47, in <module> askQ() File "qex.py", line 39, in askQ score += 1 UnboundLocalError: local variable 'score' referenced before assignment
Now, it is perfectly reasonable for me why this throws me an error on the bill. I did not install it worldwide (I commented on this part intentionally to show it). And I do not specifically use the while clause to make it move on (otherwise it will not even go into the clause). What confuses me is why this does not give me the same error for questions, choices and answers. When I uncomment these two lines, the script works fine, even without me asking questions, answers and options as global variables. Why is this? This is one thing that I could not find from searching for other questions - here it seems that Python is inconsistent. Is this because I use lists as other variables? Why is this?
(Also, the first time to the poster, thanks for all the help I found until you need to ask questions.)