0

I'm trying to code a quiz game, which every time you get a correct answer adds 1 point; at the end of the game the program prints out the number of points. The thing is, I'm trying to code it by using a function.

def qea(x, y, z):
    if x == y:
        print("Correct!")
        z += 1
    else:
        print('Wrong!')

points = 0

question1 = input("Who is the president of USA?: ").upper()
answer1 = "JOE BIDEN"
qea(question1, answer1, points)

question1 = input("Alexander...: ").upper()
answer1 = "THE GREAT"
qea(question1, answer1, points)

print(points)

Why is the program output always 0?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Does this answer your question? [Can not increment global variable from function in python](https://stackoverflow.com/questions/10506973/can-not-increment-global-variable-from-function-in-python) – mkrieger1 Oct 30 '22 at 20:55

2 Answers2

1

You should return the new value and assign it back to points:

def qea(x, y, z):
    if x == y:
        print("Correct!")
        z += 1
    else:
        print('Wrong!')
    return z

points = 0

question1 = input("Who is the president of USA?: ").upper()
answer1 = "JOE BIDEN"
points = qea(question1, answer1, points)

question1 = input("Alexander...: ").upper()
answer1 = "THE GREAT"
points = qea(question1, answer1, points)

print(points)
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

Your issue here is that the function is changing z, not points. If you change the order of your code, and also delete your z prop, then it should work.

points = 0

def qea(x, y):
    if x == y:
        print("Correct!")
        points += 1
    else:
        print('Wrong!')

question1 = input("Who is the president of USA?: ").upper()
answer1 = "JOE BIDEN"
qea(question1, answer1)

question1 = input("Alexander...: ").upper()
answer1 = "THE GREAT"
qea(question1, answer1)

print(points)
codingtuba
  • 366
  • 2
  • 13