Python Global Keyword

1) Basic Global Declaration

Create a global variable x = 5. Write a function that uses global x and prints it.


2) Modify Global Variable

Create count = 0. Inside a function, use global count and increment it by 1. Call the function and print count.


3) Multiple Increments

Using the same count, call the function 5 times and print final global count.


4) Update String Globally

Create message = "hi". Inside a function, assign a new string using global message. Print before and after the function call.


5) Global Inside Conditional

Set flag = True. Write a function with an if flag: block — modify flag globally inside it.


6) Use Global Without Modifying

Create num = 10. Inside a function use global num without changing it — just print it.


7) Two Globals in One Function

Create x = 5, y = 10. Inside a function declare both globals and swap their values.


8) Global in Loop

Make a global list nums = []. Write a function that appends values using global nums.


9) Global and Return

Modify a global variable inside a function and also return it — check if both match.


10) Global vs Local

Create a = 10. Inside a function declare global a, set a = 20, and print both inside and outside.


11) Read Global Without global

Create value = 50. Inside a function print value without using global.


12) Attempt Modify Without global

Create a global counter = 0. Inside a function try modifying it without global — note the error.


13) Global in Nested Function

Define a global variable. Inside an outer function, use a nested function to modify the global.


14) Global with User Input

Create a global user_name = "". Write a function that takes input and updates it globally.


15) Global List Modification

Create a global list of numbers. In a function, use global and change the list (e.g., sort or append).


16) Reset Global Variable

Start with score = 10. Write a function to reset it to 0 using global.


17) Global Count Even Numbers

Create a global counter. Write a function that loops 1–10 and increments the counter only for evens.


18) Global Toggle Flag

Create toggle = False. Write two functions: one sets toggle = True and another sets toggle = False.


19) Global and Default Arguments

Create a global limit = 5. Write a function def test(limit=10): that prints the global and local limit using global.


20) Global Debug

Initialize debug_mode = False. Write a function to set it to True using global, then print a message only if debug is on.


🧠 Key Concepts Practiced

Concept
What You Learn

Reading global inside a function

no global needed if not modifying

Modifying global variable

use global inside function

Global with loops

updating globals in iterative logic

Global vs local

how a local variable can shadow a global

Global with input

updating global based on runtime input


📌 Example Problem Template

Modify a Global Counter


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

Last updated