-1
def check_answer (q, a, s ):
    if q == a :
        s += 1 
        print (f" your score is {s} ")
    else : 
        s -= 1 
        print (f" your score is {s} ")

i know maybe my english not good but i need help with my problem i made a quiz project , when user enter the right answer I want the program give him more 1 point in his score but my code does not work good !!

my code return 1 only my code

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

Two options

  1. Use return value to update caller variable
  2. 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
# ...
DarrylG
  • 16,732
  • 2
  • 17
  • 23