0
0
Pythonprogramming~15 mins

Nonlocal keyword in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding the Nonlocal Keyword in Python
๐Ÿ“– Scenario: Imagine you are creating a simple counter inside a function. You want to increase the count each time you call a nested function. This project will help you learn how to use the nonlocal keyword to change a variable in the outer function from inside the inner function.
๐ŸŽฏ Goal: You will build a function with a nested function that increases a counter using the nonlocal keyword. You will then print the updated count.
๐Ÿ“‹ What You'll Learn
Create a function with a nested function
Use the nonlocal keyword to modify the outer variable
Call the nested function to increase the counter
Print the final counter value
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Using <code>nonlocal</code> helps when you want to keep track of changes inside nested functions without using global variables. This is useful in creating counters, stateful functions, or closures.
๐Ÿ’ผ Career
Understanding <code>nonlocal</code> is important for writing clean, maintainable Python code, especially when working with nested functions, decorators, or advanced function designs.
Progress0 / 4 steps
1
Create the outer function with a counter variable
Create a function called counter that has a variable count set to 0 inside it.
Python
Need a hint?

Define a function with def counter(): and inside it write count = 0.

2
Add a nested function that uses nonlocal to change count
Inside the counter function, create a nested function called increase. Use the nonlocal keyword for count inside increase. Then add 1 to count inside increase.
Python
Need a hint?

Inside counter, define def increase():. Use nonlocal count to tell Python you want to change the outer count. Then write count += 1.

3
Call the nested function and return the count
Still inside counter, call the nested function increase() once. Then return the value of count from counter.
Python
Need a hint?

Call increase() inside counter to add 1 to count. Then use return count to send the updated count back.

4
Print the result of calling counter
Call the function counter() and print its result using print(counter()).
Python
Need a hint?

Use print(counter()) to show the number 1, which is the updated count.