Skip to contentSkip to navigation

Module 5

Functions and Scope

Organize reusable code with parameters, return values, recursion, variable arguments, and introspection.

// Lessons

6

// Quiz questions

90

// Reading time

120 min

// Exam length

15 Q

// Coding exercises

10

  1. 1Functions & Modular CodePackage reusable logic with def, pass parameters, return values, and document with docstrings. 20 min 15 questions
  2. 2Positional & Keyword ArgumentsConfigure required parameters, named keyword calls, default values, and avoid the mutable default trap. 20 min 15 questions
  3. 3Variadic Arguments (*args & **kwargs)Accept arbitrary positional and keyword parameters, unpack iterables, and enforce keyword-only boundaries. 20 min 15 questions
  4. 4Variable Scope & the LEGB RuleNavigate Local, Enclosing, Global, and Built-in namespaces, closures, and the nonlocal keyword. 20 min 15 questions
  5. 5Recursion & the Call StackSolve self-referential problems with termination base cases, stack frame tracing, and recursion limits. 20 min 15 questions
  6. 6Code Introspection & MetadataInspect live objects, docstrings, annotations, and module namespaces at runtime using built-in reflection. 20 min 15 questions

Coding practice: write it yourself

Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (4 exercises)

All module exercises

Coding practice needs an account. Sign in or create a free ID to run these exercises.

Lab 1: Write double()

Sign-in required

Write a function double(n) that RETURNS n multiplied by 2, then print double(21).

Coding Practice is Locked

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.

Lab 2: Celsius to Fahrenheit

Sign-in required

Write to_f(c) returning c × 9/5 + 32, rounded to 1 decimal. Print to_f(37).

Coding Practice is Locked

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.

Lab 3: Greeting with a default

Sign-in required

Write greet(name, greeting="Assalamu alaikum") returning "greeting, name!". Print greet("Mim") and then greet("Rafi", "Hello") — two lines.

Coding Practice is Locked

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.

Lab 4: Sum any number of bills

Sign-in required

Write total(*bills) that accepts ANY count of amounts and returns their sum. Print total(120, 80.5, 60).

Coding Practice is Locked

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.

References & Further Reading

Related entries from PyLabs's own reference library.

  • callable() (Check whether an object can be called with parentheses.)
  • locals() (Get the local names currently available in this part of the code.)
  • sorted() (Make a new list containing items in sorted order.)