简体   繁体   English

python更改函数中的全局字符串

[英]python change global string in function

First off i am very new to coding and python. 首先,我对编码和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. 我尝试使用return(),但是它只是退出了程序。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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