0

We're making a simple MUD as a sort of "learn how to program in Python" project. We'd like it to be persistent, so we have a MySQL database for the Python scripts to save to. However, we're sort of stuck right now with pulling an integer from the database, adding to it, and saving it once again. Here's my code:

initxp = cur.execute("SELECT Exp FROM CharactersDB WHERE ID=%s", name)
print "initxp is,", initxp
global xp
xp = int(initxp)
print "current xp is ", xp

global xpcounter
xpcounter = ("UPDATE CharactersDB SET Exp=%s WHERE ID=%s") #where is name variable


#save initial xp to db
cur.execute(xpcounter, (xp, name,))
db.commit()

#when you gain xp
def gainxp():
    global xp
    global xpcounter
    xp = xp + 10
    print name, "gains", xp, "xp!"
    #save new xp to db
    cur.execute(xpcounter, (xp, name,))
    db.commit()
    return xp


#save stats to the database,
#this funciton will be used in the character creation file

gainxp()

I don't have any errors, though I do have some weird things happening:

Firstly, when it prints the "initxp" variable, it returns with 1 every time. As does the "Current xp" line. So, when it enters into the gainxp() function, it just adds 1 to 10, saves the grand total of 11 and is on its merry way.

What we'd like to do is take that already saved 11 xp, add another 10 to it, save it, run it again and have another 10 added to it so we have 31xp, not a consistent 11 every time, which obviously defeats the purpose.

Thanks!

1 Answer 1

1

cur.execute returns the number of rows affected - in your case, just 1 row, which is why it always returns 1. To get the actual value, you need to do cur.fetchone(), which will return a tuple of values - again, in your case, a tuple containing a single int.

Just an additional tip, since this is a 'learn Python' exercise: global variables are usually frowned on. You should pass xp explicitly into your gainxp function.

Sign up to request clarification or add additional context in comments.

2 Comments

I've read that global variables are generally frowned upon, but didn't know what to do otherwise... you all would probably hate our code with the number of globals we have..... At any rate, thanks! This fixed things up nicely.
Define the function as def gainxp(xp), and pass it in and store the return value: xp = gainxp(xp).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.