【问题标题】:What is wrong with this integer return code? [duplicate]这个整数返回码有什么问题? [复制]
【发布时间】:2020-08-01 06:20:34
【问题描述】:
points = 0

def testfunction():
    points = 2
    return points

testfunction()
print (points)

为什么点数现在不等于 2?

【问题讨论】:

    标签: python string function return


    【解决方案1】:

    在这里,testFunction 在其本地范围内创建另一个 points 变量。这就是为什么全局points 变量的值没有改变的原因。您需要告诉您的函数您要使用全局 points 变量,

    points = 0
    
    def test_function():
        global points
        points = 2
        return points
    
    test_function()
    print(points)
    

    或者你可以将返回值赋给points变量,比如:

        def test_function():
            points = 2
            return points
    
        points = test_function()
        print(points)
    

    而且大多数 Pythonistas 更喜欢使用蛇形大小写来命名函数和变量。

    【讨论】:

      【解决方案2】:

      你必须将变量分配给函数,写:

      points = testfunction()
      

      打印线上方。

      【讨论】:

        【解决方案3】:

        函数中的return 必须分配给变量。您可以像这样编辑全局变量:

        points = 0
        
        
        def test_function():
            global points
            points = 2
            pass
        
        
        test_function()
        print(points)
        

        或者不调用点作为全局变量:

        points = 0
        
        
        def testfunction():
            points = 2
            return points
        
        
        points = testfunction()
        print (points)
        

        显然这确实使points 的初始声明相当过时......

        【讨论】:

          【解决方案4】:

          在函数内部创建的变量属于该函数的局部作用域,只能在该函数内部使用。

          因此,即使它们具有相同的名称,您也无法从函数中修改外部变量。

          你可以使用:

          points = testfunction()
          

          【讨论】:

            【解决方案5】:

            您有两个不同的变量,名称为 points。一个在外部作用域中声明,另一个是本地函数testfunction()

            外部范围points 变量设置为 0 并且永不更新。本地范围points 设置为2从函数返回,然后蒸发到遗忘。函数返回的值本质上是向左“吐出”,可用于赋值到另一个变量。

            因此:

             points = 0
            
             def testfunction():
                  points = 2
                  return points
            
             points = testfunction()
             print (points)
            

            会完成你想要的。

            这样写可能更清楚:

             calc_result = 0
            
             def testfunction():
                  points = 2
                  return points
            
             calc_result = testfunction()
             print (calc_result )
            

            另外,因为 Python 不需要任何类型的变量声明,所以不需要第一行。

            【讨论】:

              猜你喜欢
              • 2021-10-06
              • 1970-01-01
              • 2017-12-09
              • 2017-08-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-04-11
              • 2015-06-10
              相关资源
              最近更新 更多