Guide
Python
Intermediate
6.15 Hands-on Exercises
Practice programs and mini projects for reinforcing Python variable and memory management concepts — UnboundLocalError, shallow vs deep copy, closures, environment-based configuration, and reference tracing.
Practice Programs
- Write a function demonstrating
UnboundLocalError, then fix it using theglobalkeyword. - Given a nested list, show the difference between
copy.copy()andcopy.deepcopy()by mutating a nested element. - Write a closure using
nonlocalto implement a simple counter.
Mini Projects
- Configuration loader — build a small config loader that reads settings from environment variables with sensible defaults, using 6.11 Variables in DevOps as a starting point.
- Reference tracer — build a tool that takes any object and prints its
id(),type(), andsys.getrefcount()before and after a mutation, to make the concepts from 6.2 Objects and Variable References and 6.6 Garbage Collection concrete.
Quick Interview Answer
“These exercises reinforce the chapter’s core ideas hands-on: the
UnboundLocalError-then-fix exercise exercises scope and theglobalkeyword; the shallow-vs-deep-copy exercise exercises reference sharing on nested mutable objects; thenonlocalcounter exercises closures and enclosing scope; and the reference tracer ties identity, type, and reference counting together into one small diagnostic tool.”
Common Mistakes
- Skipping the shallow-vs-deep-copy exercise as “just theory” — it’s one of the most common real bugs when working with nested config dicts or lists of records.
- Building the reference tracer without accounting for the temporary reference
sys.getrefcount()’s own call creates, and misreading the count as a result.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form