In Python, variables can have different scopes, primarily local and global. The scope of a variable determines where in the code it can be accessed and modified. Here are some examples and exercises to illustrate the concept of local and global scope:
Global Scope: A variable defined outside of any function or block has a global scope. It can be accessed and modified from anywhere in the code.
Example:
global_var = 10
def print_global():
print("Global variable:", global_var)
print_global() # Output: Global variable: 10
def modify_global():
global global_var
global_var += 5
modify_global()
print("Modified global variable:", global_var) # Output: Modified global variable: 15
Local Scope: A variable defined inside a function has a local scope. It can only be accessed and modified within that function.
Example:
def local_scope_example():
local_var = 5
print("Local variable:", local_var)
local_scope_example() # Output: Local variable: 5
# Trying to access local_var outside the function will result in an error
# print(local_var) # This will raise a NameError
Exercises:
- Create a global variable
x
with a value of 20. Write a functionmultiply_by_2
that takes an argumentnum
and multiplies it by the global variablex
. Call the function with an argument of 5 and print the result. - Write a function
outer_function
that defines a local variabley
with a value of 10. Insideouter_function
, define another functioninner_function
that prints the local variabley
. Callouter_function
and then callinner_function
from within it. - Create a global variable
total
with an initial value of 0. Write a functionadd_to_total
that takes an argumentnum
and adds it to the global variabletotal
. Call the function multiple times with different values and print the final value oftotal
after all calls. - Define a variable
message
with a string value in the global scope. Write a functionprint_message
that prints themessage
variable. Inside the function, define a local variablemessage
with a different string value and print it. Callprint_message
and observe the output.
These exercises will help you understand and practice working with local and global variable scopes in Python.
One Response