global keyword in python

本小妞迷上赌 提交于 2021-02-08 04:51:13

问题


I'm studying python, and getting struggle with the global keyword within vscode. So far the code is working, but the vscode linter is raising an error, and I would like to understand why

I've tried using the global keyword, and the code works fine even though I got a linter error. I try using a local variable and didn't get any error

def whatIs ():
    global myvalue
    myvalue +=10
    print("myvalue: {}".format(myvalue))

myvalue=10

whatIs()

print("myvalue: {}".format(myvalue))

The linter points to the myvalue in the function :

Undefined variable 'myvalue' pylint(undefined-variable)

But the output is what I expect.

myvalue: 20
myvalue: 20

It's like vscode doesn't like the global keyword


回答1:


Try moving this line

myvalue=10

before the definition of WhatIs function.

myvalue=10

def whatIs ():
    global myvalue
    myvalue +=10
    print("myvalue: {}".format(myvalue))

whatIs()

print("myvalue: {}".format(myvalue))


来源:https://stackoverflow.com/questions/56097539/global-keyword-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!