Python Variable Scope

1) Local Variable

Write a function that creates a local variable x = 10 and prints it inside the function. Call the function.


2) Local vs Global

Create a global variable a = 5. Write a function that defines a local variable also named a = 10 and prints it. After calling the function, print the global a.


3) Modify Global

Create a global variable count = 0. Write a function that increments count using the global keyword.


4) No Global Keyword

Do the same as #3 without global, and observe the result.


5) Nested Function Scope

Write a function outer() that defines a variable msg = "hello". Inside it, define inner() that prints msg. Call inner() from outer().


6) Shadowing

Create a global variable num = 100. Inside a function define a local num = 50 and print both local and global values.


7) Access Before Assignment

Write a function that prints a variable before it’s defined inside the function — handle the error.


8) Parameter Scope

Define:

Call it with user input.


9) Return Local Value

Write a function that creates a local variable x = 20 and returns it. Print outside the function.


10) Modify List Inside Function

Pass a list into a function and append a value. Print the modified list outside.


11) Variable Not Defined

Try to print a local variable outside its function — observe the error.


12) Global in Branch

Create global flag = False. Inside a function, use global flag and change it to True. Print before and after calling.


13) Reassign Without global

Try to change a global variable inside a function without using global, and explain why it didn’t change.


14) Default Argument and Scope

Write a function with a default argument and print it — then override on call.


15) Function with Same Name Globally

Define a global variable and a function with the same name — explore behavior.


16) Global List Modification

Create a global list. Inside a function, modify its elements without reassigning the list — print before and after.


17) Nested Function with Outer Modification

Define a nested function that tries to modify an outer function’s variable. Use nonlocal (or show error if not used).


18) Global Integer Modify

Create x = 1. Inside a function, modify x using global and print both inside and outside.


19) Variable Scope in Loop

Write a for loop that defines a variable and print it after the loop (test visibility).


20) Scope and Input

Ask user for a number inside a function and return it; print outside.


🧠 Core Concepts Practiced

Concept
Example in Assignments

Local variable

#1, #9

Global variable

#2, #3, #12

global keyword

#3, #18

Nested scope

#5, #17

Parameter scope

#8

Variable shadowing

#6

Mutable vs Immutable in functions

#10, #16


💡 Short Example

Local vs Global

Output:


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated