what is scope in python
Python hosting: Host, run, and code Python in the cloud!
Scope
Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used. Python supports global variables (usable in the entire program) and local variables.
By default, all variables declared in a function are local variables. To access a global variable inside a function, it’s required to explicitly define ‘global variable’.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Example
Below we’ll examine the use of local variables and scope. This will not work:
#!/usr/bin/python |
but this will:
#!/usr/bin/python |
Let’s examine this further:
#!/usr/bin/python |
Calling functions in functions
We can also get the contents of a variable from another function:
#!/usr/bin/python |
If a variable can be reached anywhere in the code is called a global variable. If a variable is known only inside the scope, we call it a local variable.
If you are new to Python programming, I highly recommend this book.
Leave a Reply:
I ran this code in v2.7.10 and it executed without any errors
Try this program:
In this example z will still be 3 after calling f(3,2). Sorry for the confusion, ill update
So without "global z" in function 'f' z is local to the function and when you return back the global z is scoped.
Correct, otherwise the changed occur only locally
To follow up on Carl's comment, the supplied example in the tutorial (with the bold, italic "this will not work") also works fine for me in Python 3.6. I thought I'd let everyone know what I discovered while experimenting to find what would and would not work.
Without using the keyword 'global'...
You can reference a global variable inside a function. This code works fine, and prints the global value of z (10) twice:
You can also create a local variable with the same name inside a function. This code works fine, and prints the local value of z (1) followed by the global value of z (10):
However, you cannot first reference global variable then create a local variable with the same name. Trying to define testing_scope like this does not work:
I hope that helps clarify things!
My apologies for the indentation not showing up properly. I would edit if I could.
No problem, all indented correctly now :)