global keyword in python

Asked by At

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 Answers

0
Manu mathew On Best Solutions

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