Home > Software design >  Creating quiz game with function does not update the global score variable
Creating quiz game with function does not update the global score variable

Time:10-31

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?

CodePudding user response:

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)

CodePudding user response:

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, z):
    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)
  • Related