Two options
- Use return value to update caller variable
- Use global variable so function uses caller's variable s
Note: Option 1 is normally preferred with Option 2 only for simple code.
Issue with Option 2 is global variables enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity--Source
Option 1--use return to update s
def check_answer (q, a, s ):
# a local s is initialized to the passed-in value
if q == a :
s += 1 # update local s in function check_answer
print (f" your score is {s} ")
else :
s -= 1 # update local s in function check_answer
print (f" your score is {s} ")
return s # returns the value of the local s to caller
# Usage (as mentioned by Barmar in comments)
# Initialization (set s to initial value)
s = 0
# ... some code
s = check_answer(q1, a1, s) # s is updated to new value
# ...some more code
s = check_answer(q1, a2, s) # s is udpated to new value
# ...and so on
Option 2: share s as a global variable
def check_answer (q, a):
global s # use s from global scope
if q == a :
s += 1 # updates global variable s
print (f" your score is {s} ")
else :
s -= 1 # updates global variable s
print (f" your score is {s} ")
# Usage
# initialize s (global scope variable i.e. outside function calls)
s = 0
# other code
# ...
check_answer (q1, a1) # global s is updated
# ...
# ...
check_answer(q2, a2) # global s is updated
# ...and so on
# ...