Python Scope
- The place where a variable is created defines its availability to be accessed and manipulated by the rest of the code. This is known as scope.
There are two types of scope:
Local Scope
Global Scope
1. Local Scope
- When you declare a variable inside a function it only exists inside that function and can't be accessed from the outside.
- The variable name was declared inside the function, the output is the same as before:
- But this will throw an error.
2. Global Scope
- A global scope allows you to use the variable anywhere in your program.
- If you variable is outside a function, it has global scope by default.
Note : That the function could use the variable name and print my name is Programmerfect.
Mixing Scopes
- If you use the same name of variables inside and outside a function, the function will use the one inside its scope.
- So when you call print_name(), the name="Programmerfect" is used to print the phrase.
- On the other hand, When calling print() outside the function scope, name="Richard Rahul" is used because of its global scope.
Comments
Post a Comment