简体   繁体   中英

python change global string in function

First off i am very new to coding and python. I am trying to call a global string inside of a function. Then I want to change it into an integer. Next, I want to apply some Math to the integer. Finally I want to convert that integer back to a string and send it back to the global to use in other functions.

I have accomplished most of what I needed to do, but I am having trouble sending the string back to the global. I have tried using return() but it just quits the program. Instead I want it to go to another function, while retaining the new value

Relevant code

current_gold = '10'

def town():
    global current_gold
    print(current_gold)

def pockets():
    global current_gold
    new_gold = int(current_gold) + 5
    new_gold = str(new_gold)
    print(new_gold.zfill(3))


    input("\tPress Enter to return to town")
    town()

This is not the full code. I maybe doing stuff drastically wrong though.

current_gold = '10'
def changeToInt():
    global current_gold
    current_gold = int(current_gold)

print(type(current_gold)) # It's a string right now
changeToInt() # Call our function
print(type(current_gold)) # It's an integer now

Or you could do it by passing a parameter to your function like so:

current_gold = '10'
def changeToInt2(aVariable):
    return int(aVariable)

print(type(current_gold)) # It's a string right now
current_gold = changeToInt2(current_gold) # make current_gold the output of our function when called with current_gold as aVariable
print(type(current_gold)) # It's an int now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM