Python 从while循环中定义的函数访问变量

Python 从while循环中定义的函数访问变量,python,while-loop,Python,While Loop,我的代码与此类似 v = '0' def program(): x = input('1 or 2 ') if x == '1': print('it is 1') v = '1' elif x == '2': print('it is 2') v = '2' while True: program() print(v) 但是,当我运行此代码时,变量“v”总是打印出默认的0。 为什么它不

我的代码与此类似

v = '0'

def program():
    x = input('1 or 2 ')
    if x == '1':
        print('it is 1')
        v = '1'
    elif x == '2':
        print('it is 2')
        v = '2'

while True:
    program()
    print(v)
但是,当我运行此代码时,变量“v”总是打印出默认的0。
为什么它不给我在函数中分配的变量?

您的函数操作变量
v
的本地副本。如果要在调用
program()
后获取v的值,请在函数定义的末尾追加
return v
。 即:

如果不想返回任何内容,可以将
v
设置为全局声明的变量,如下所示:

v = '0'

def program():
    x = input('1 or 2 ')
    if x == '1':
        print('it is 1')
        global v
        v = '1'
    elif x == '2':
        print('it is 2')
        global v
        v = '2'

while True:
    program()
    print(v)

为了补充复制标志,以下是有关代码的说明:

您需要明确地告诉您的方法您想要使用全局
v
,否则,它将永远不会从方法范围内发生的
v
中得到更新

要纠正此问题,您需要在方法中添加
global v

def program():
    global v
    # rest of your code here

这应该行得通

Python中的变量赋值是局部范围的。如果要在函数内部操纵全局状态(或封闭状态),可以将该状态包装在保持器中,然后引用保持器。例如:

v = ['0']

def program():
    x = input('1 or 2 ')
    if x == '1':
        print('it is 1')
        v[0] = '1'
    elif x == '2':
        print('it is 2')
        v[0] = '2'

while True:
    program()
    print(v[0])

上面的段引用一个数组并操作数组内部的值。

您有两个名为
v
的变量:

  • 全局级别
    v=0
    声明位于顶部
  • 程序中
    v
    的函数声明
  • 首先,您真的不应该在函数中使用全局变量,因为这是一种糟糕的编程实践。您应该将其作为参数传递,并返回任何其他结果

    如果确实需要,可以通过首先将全局变量声明为全局变量来修改函数中的全局变量

    还要注意的是,您需要在Python 2中使用
    raw_input

    def program():
        global v
        x = raw_input('1 or 2 ')
        if x == '1':
            print('it is 1')
            v = '1'
        elif x == '2':
            print('it is 2')
            v = '2'
    

    您使用的是哪个版本?您会在这里找到一个很好的答案:您可能想解释一个如何更改变量的实际id,而另一个只是修改变量引用的对象。解释得很好。好的建议就坏的做法提出来。
    def program():
        global v
        x = raw_input('1 or 2 ')
        if x == '1':
            print('it is 1')
            v = '1'
        elif x == '2':
            print('it is 2')
            v = '2'