简体   繁体   English

我在python中更改/更新全局变量时遇到问题

[英]Im having trouble with changing/updating global variables in python

So I was having trouble understanding the basics of global variable as I am a beginner in python. 因此我无法理解全局变量的基础知识,因为我是python中的初学者。 I wanted to try to change a global variable but unfortunate it didn't work. 我想尝试更改一个全局变量但不幸的是它没有用。 Could any of you explain and help my fix my problem. 你们任何人都可以解释并帮助我解决我的问题。 Thanks!! 谢谢!!

global x
x = 10
def NEWX():
     print (x)
     x = x + 5
     print (x)
print (x)
NEWX()
print(x)

#this displays 10 10 15 10

Try this refactor: 试试这个重构:

x = 10


def new_x():
    global x
    print(x)
    x = x + 5
    print (x)


print(x)
new_x()
print(x)

# prints 10 10 15 15

I was unable to run your original code, it complained about x being undefined in the function. 我无法运行您的原始代码,它抱怨x在函数中未定义。 Within the scope of the function, x is unknown. 在函数范围内, x是未知的。 It's known at the higher scope, but not in your function. 它在更高的范围内是已知的,但在您的功能中却不是。 That's why the global x statement needs to be in the function - to let python know to use the x from the outer scope. 这就是为什么global x语句需要在函数中的原因-让python知道在外部范围内使用x

x = 10

def NEWX():
     global x
     print (x)
     x = x + 5
     print (x)

print (x)
NEWX()
print(x)

Global variable rules: 全局变量规则:

  • global keyword outside a function has no effect 函数外的全局关键字无效
  • Variable outside a function is global by default 函数外部的变量默认为全局变量
  • global keyword is needed to read and write global variable within a function 需要全局关键字来读写函数中的全局变量

In your code, you are first printing the value of x. 在代码中,您首先要打印x的值。 The function NEWX(): is then called which prints x, then adds 5 onto x and prints the new value. 然后调用函数NEWX():打印x,然后将5加到x上并打印新值。 After the function is called, x is printed again. 调用函数后,将再次打印x。

To understand what is happening, check out this example that contains the fix: 要了解发生了什么,请查看包含修复程序的以下示例:

 x = 10

def NEWX():
    print (x)
    global x
    x = x + 5
    print (x)
print (x)
NEWX()
print(x)

在此输入图像描述

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

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