[英]Assigning variables inside a function
this question is probably so common that it is being asked every other minute but I've tried to look for answers and couldn't find it. 这个问题可能很常见,以至于每隔一分钟就会被问到,但我试图寻找答案,却找不到。 Most likely I wasn't able to phrase the question well enough.
我很可能无法很好地表达这个问题。
Anyway, I'm working on a small text-game and it has variables, for simplicity let's say water = 100
. 无论如何,我正在开发一个小型的文字游戏,它具有变量,为简单起见,假设
water = 100
。 And I have a function that is the main
loop. 我有一个功能是
main
循环。 Let's say the code looks something like this: 假设代码看起来像这样:
water = 100
def main():
while True:
water -= 5
print(water)
main()
Of course, when I run this program it tells me that the variable was referenced before assignment. 当然,当我运行该程序时,它告诉我变量在赋值之前已被引用。 But if I make the variable inside the function then with each iteration of the loop it will reset the variable to the original 100.
但是,如果我在函数内创建变量,则每次循环迭代时,它将变量重置为原始100。
So how do I make this work? 那我该如何做呢? Thanks!
谢谢!
Use keyword global
. 使用关键字
global
。 In your code declare in function global water
before the loop and then your code will work fine. 在您的代码中,在循环之前在函数
global water
声明,然后您的代码将正常工作。
If you want to write your code without using globals, you can also write your code to use nonlocal
variables as well. 如果要编写代码而不使用全局变量,也可以编写代码以使用
nonlocal
变量。 However, this may be ever more confusing and inappropriate for what you are trying to do. 但是,对于您尝试做的事情,这可能会变得更加混乱和不合适。 PatNowak 's answer has encouraged you to read about the
global
keyword. PatNowak的答案鼓励您阅读有关
global
关键字的信息。 Use the following example as an encouragement to also read about variables that are not exactly local or global. 使用下面的示例作为鼓励,也可以阅读不完全是局部或全局的变量。
def create_functions():
water = 100
def first_function():
nonlocal water
for _ in range(10):
water -= 5
print(water)
def second_function(amount):
nonlocal water
water += amount
return first_function, second_function
main, add_water = create_functions()
main()
add_water(25)
main()
if I make the variable inside the function then with each iteration of the loop it will reset the variable to the original 100.
如果我在函数内创建变量,则每次循环迭代时,它将变量重置为原始100。
??? ???
def main():
water = 100
while water > 0:
water -= 5
print(water)
main()
Output: 输出:
95
90
85
80
75
70
65
60
55
50
45
40
35
30
25
20
15
10
5
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.