I am learning Python and am making a Q&A script. I made one function for the questions. That went rather well. Now I am wanting an average function. I want to avoid using globals if at all possible. I know that my variables reset at the top… can someone please give me some pointers? I know C/PHP/BASIC and want to grasp this langauge. Below is my question function.
def q(question, a, b, c, c_answer):
total,tally=0,0
print "",question
print " a.",str(a)
print " b.",str(b)
print " c.",str(c)
u_answer = raw_input()
if c_answer == "a" and u_answer == "a":
print "Correct, the answer is A!"
tally+=1
elif c_answer == "b" and u_answer == "b":
print "Correct, the answer is B!"
tally+=1
elif c_answer == "c" and u_answer == "c":
print "Correct, the answer is C!"
tally+=1
else:
print "I am sorry, but the correct answer is",c_answer
print "\..n"
total+=1
Since you’re just learning Python, I reformatted your code to be more pythonic.
To actually answer your question:
There a couple ways to keep track of the total number of questions and correct answers without using global-level variables (actually module-level, but that’s a different topic ;).
One is to pass in the current totals, have
qrecalculate based on the current question, and then pass them back out:Then in your main program you can say:
However, it would be better for
qto just deal with questions, and not worry about keeping track of how many questions have been answered and how many questions have been asked.So instead of accepting
totalandtally, recalculating, and returningtotalandtally,qwill now just return0if the answer was wrong,1if it was correct:and the rest of the code looks like: