函数不更新全局变量

我有以下功能


 class calculation()

       

       x=3

    

       def calculateOO(y):

          global x

          x=3*y

     

       calculateOO(2)

            

       print(x)

答案是 3,而不是 6。该函数没有效果。


函数有什么问题吗?


至尊宝的传说
浏览 115回答 3
3回答

繁花如伊

适当的缩进:x=3def calculateOO(y):    global x    x=3*ycalculateOO(2)print(x)   # 6

白板的微信

我认为您对全局变量、返回语句和函数感到困惑。尝试一下并阅读我的内联评论:x=3def calculateOO(y):    global x    x=3*ydef calculateXX(z):    y=3*z    return yprint(calculateOO(2))#prints None, as the function has no return statementprint(x)#prints 6, as we set x to be global in the calculateOO() function aboveprint(calculateXX(2))#prints 6, as we return the value inside the functionprint(y)#causes an error, as we did not set a global y

守着星空守着你

您还可以执行以下操作:x=3def calculateOO(y):    global x    x=3*y    return  print((3*y),x)calculateOO(2)希望这个解决方案对您有所帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python