函数未更新全局变量

时间:2020-09-09 14:13:16

标签: python

我具有以下功能

 class calculation()
       
       x=3
    
       def calculateOO(y):
          global x
          x=3*y
     
       calculateOO(2)
            
       print(x)

答案是3,而不是6。该函数无效。

该功能有什么问题?

3 个答案:

答案 0 :(得分:2)

缩进正确:

geom_text()

答案 1 :(得分:0)

您还可以执行以下操作:

x=3

def calculateOO(y):
    global x
    x=3*y
    return  print((3*y),x)

calculateOO(2)


希望此解决方案对您有帮助

答案 2 :(得分:0)

我认为您对全局变量,返回语句和函数感到困惑。玩这个,并内联阅读我的评论:

x=3
def calculateOO(y):
    global x
    x=3*y

def calculateXX(z):
    y=3*z
    return y

print(calculateOO(2))
#prints None, as the function has no return statement
print(x)
#prints 6, as we set x to be global in the calculateOO() function above

print(calculateXX(2))
#prints 6, as we return the value inside the function
print(y)
#causes an error, as we did not set a global y