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

时间:2016-03-02 00:20:13

标签: 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。 为什么不给我我在函数中指定的变量?

4 个答案:

答案 0 :(得分:2)

您有两个名为v的变量:

  1. 顶部的全球级v=0声明。
  2. 程序中v的函数声明。
  3. 首先,你真的不应该在函数中使用全局变量,因为这是糟糕的编程习惯。您应该将其作为参数传递,并返回任何其他结果。

    如果你真的必须,你可以通过首先将它声明为全局变量来修改函数中的全局变量。

    另请注意,您需要在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'
    

    Using global variables in a function other than the one that created them

答案 1 :(得分:1)

您的函数操纵变量v的本地副本。如果您想在调用program()后获取v的值,请将return v附加到函数定义的末尾。 那就是:

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'
    return v

while True:
    v = program()
    print(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)

答案 2 :(得分:1)

为了补充重复标记,以下是对您的代码的解释:

您需要明确告诉您的方法您要使用全局v,否则,它将永远不会从方法范围内的v更新。

要解决此问题,您需要在方法中添加global v

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

那应该有用。

答案 3 :(得分:1)

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])

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

相关问题