How do i use variable scope in python?
-
Variable scope is the scope of the variable and whether it is available outside of a method or inside of a method.
Define a variable outside the method, and define one inside the method, then print the variable.
>>> myvar = "carrot" >>> def best_cake(myvar): print("We like " + myvar + " cake, I run before method is ran") myvar = "fruit" print("We like " + myvar + " cake, I run after method is ran") >>> print("I'm a global cake: " + str(myvar))
I'm a global cake: carrot
Run the method.
>>> best_cake(myvar)
We like carrot cake, I run before the method is run
We like fruit cake, I run after the method is ranConclusion: The global variable used until the method is run
You can change the global variable by using the global statement.
Add the statement "global myvar" to the code.
>>> def best_cake(): global myvar print("We like " + myvar + " cake, I run before the method is ran") myvar = "fruit" print("We like " + myvar + " cake, I run after the method is ran") >>> print("I'm a global cake: " + str(myvar))
I'm a global cake: carrot
Run the method.
>>> best_cake()
We like carrot cake, I run before the method is ran
We like fruit cake, I run after the method is ranPrint the global variable again. Notice, it change the variable from carrot to fruit.
>>> print("We like " + myvar + " cake")
We like fruit cake
Conclusion: Using the global statement inside the method change the value of the variable outside of the method.
© Lightnetics 2024