Python Worksheet: Local vs Global Variables
Name: ______________________ Date: ________________
Part 1: Fill in the Blanks
1. A variable defined inside a function is called a ______________ variable.
2. A variable that is defined outside all functions is called a ______________ variable.
3. Local variables can only be accessed _____________ the function.
4. To modify a global variable inside a function, use the keyword: ______________.
Part 2: Identify the Variable Type
Write L for Local and G for Global next to each variable.
x = 100 # _____
def test():
y = 50 # _____
print(y)
test()
print(x)
Part 3: Code Output
What will be the output of the following code?
name = "Ali"
Page 1
Python Worksheet: Local vs Global Variables
def greet():
name = "Sara"
print("Hello", name)
greet()
print("Outside function:", name)
Your Answer:
Hello __________
Outside function: __________
Part 4: Write Your Own Code
Write a Python program that:
1. Creates a global variable named 'city'
2. Creates a function that prints 'city'
3. Then inside the function, create a local variable called 'area' and print it too.
Page 2