【问题标题】:Accessing a variable from a defined function in a while loop [duplicate]在while循环中从定义的函数访问变量[重复]
【发布时间】:2016-03-02 00:20:13
【问题描述】:

我有类似这样的代码

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。 为什么它没有给我我在函数中分配的变量?

【问题讨论】:

标签: python while-loop


【解决方案1】:

您有两个名为 v 的变量:

  1. 顶部的全局级别v=0 声明。
  2. 程序中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'

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

【讨论】:

  • 很好的解释。好呼吁提及不良做法。
【解决方案2】:

您的函数操作变量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)

【讨论】:

    【解决方案3】:

    为了补充重复标志,这里是关于您的代码的解释:

    您需要明确告诉您的方法您要使用全局v,否则,它永远不会根据方法范围内v 发生的情况进行更新。

    为了纠正这个问题,你想在你的方法中添加global v

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

    应该可以。

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 您可能想解释一个如何更改变量的实际 id 而另一个只是修改变量引用的对象。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多