Q:

Trouble with global variables in pygame

I am trying to make an experience system for my summer game project but for some reason it does not seems to carry over to the function of experience system. Here is what I did:
global currentxp
currentxp = 0
global level
level = 1
def exp_system():
    import random
    mobxp = random.randrange(1, 20, 1)
    currentxp = currentxp
    currentxp = currentxp + mobxp
    level = currentxp
    if currentxp >= 100:
        print("You Leveled Up!")
        level_up = True
    if currentxp < 100:
        level_up = False
        print("You need more xp to level up!")
    if level_up:
        currentxp = 0
        print("Your Current XP is now:")
        print(currentxp)
        level = level + 1
        print("You current level is now:")
        print(level)
        improvestst = input("Choose a stat to improve:(Health or Attack Power)")
    else:
        print("Your Current XP is now:")
        print(currentxp)
        print("You current level is now:")
        print(level)

To test the system I used the following:
mobhealth = 0
if mobhealth >= 0:
    victory = True
if victory:
    exp_system()
    victory = False

However I am getting UnboundLocalError: local variable 'currentxp' referenced before assignment on currentxp = currentxp on the Python console. I hope someone can tell me what I did wrong and give an example using my variables. Thanks!

A:

I would do away with the globals and just pass in and return the variables.
import random

currentxp = 0
level = 1

def exp_system(currentxp, level):

    mobxp = random.randrange(1, 20, 1)
    currentxp = currentxp + mobxp

    if currentxp >= 100:
        print("You Leveled Up!")
        level_up = True
    if currentxp < 100:
        level_up = False
        print("You need more xp to level up!")
    if level_up:
        currentxp = 0
        print("Your Current XP is now:")
        print(currentxp)
        level = level + 1
        print("You current level is now:")
        print(level)
        improvestst = input(
            "Choose a stat to improve:(Health or Attack Power)")
    else:
        print("Your Current XP is now:")
        print(currentxp)
        print("You current level is now:")
        print(level)

    return currentxp, level

mobhealth = 0
if mobhealth >= 0:
    victory = True
if victory:
    currentxp, level = exp_system(currentxp, level)
    victory = False

Output:
You need more xp to level up! Your Current XP is now: 17 You
current level is now: 1

Your conditionals are overly complicated. Keep it simple is a great rule for programmers.
if currentxp >= 100:
    print("You Leveled Up!")
    currentxp = 0
    level = level + 1
    improvestst = input("Choose a stat to improve:(Health or Attack Power)")
else:
    print("You need more xp to level up!")
print("Your Current XP is now:")
print(currentxp)
print("You current level is now:")
print(level)

The above code does the same stuff (in a slightly different order) with less code.

