How do I use the global variable in Python?

Asked 2 years ago, Updated 2 years ago, 13 views

Running the code below. in the call of a func globvar was not declared . Maybe globvar = 3 , global variables I think so because she's not how variables are all over in Python?

SyntaxError: Missing parentheses in call to 'print'

globVar = 3

def func1():
    globVar+=1

def func2():
    print globVar

func1()
func2()

python

2022-09-21 18:49

1 Answers

Python uses most variables as local variables by default. Therefore, globVar of globVar=3 and globVar of func1 are variables in different scopes, only with the same name When you invoke func1, an error appears that globVar has not been declared.

The keyword for declaring a global variable is global. If you have any questions

def func1():
    global globVar
    globVar = 3
    globVar+=1

def func2():
    print globVar

func1()
func2()

You can write it with.


2022-09-21 18:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.