Module 4
>Functions and Modules
Organize reusable code with functions, modules, and practical built-in tools.
// Lessons
5
// Quiz questions
50
// Reading time
57 min
// Exam length
15 Q
// Coding exercises
9
- 1FunctionsDefine, call, and return values from functions so you can reuse clear pieces of code. 10 min 10 questions
- 2Function ArgumentsPass values to functions safely with positional, keyword, default, variable, and named arguments. 12 min 10 questions
- 3Scope and RecursionControl where names exist and solve repeatable problems with safe recursive functions. 12 min 10 questions
- 4Lambda and Built-in FunctionsUse short lambda functions and Python built-ins to sort, transform, filter, and check data. 12 min 10 questions
- 5Modules and PackagesImport useful code from modules, understand packages, and recognize a script's main entry point. 11 min 10 questions
Coding practice: write it yourself
Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (0/4 passed this visit)
You can run every exercise now. Create a free ID to keep passes, code attempts and XP.
Lab 1: Write double()
Not passed yetWrite a function double(n) that RETURNS n multiplied by 2, then print double(21).
def double(n):
# return the doubled value
print(double(21))
Lab 2: Celsius to Fahrenheit
Not passed yetWrite to_f(c) returning c × 9/5 + 32, rounded to 1 decimal. Print to_f(37).
def to_f(c):
# convert and round
print(to_f(37))
Lab 3: Greeting with a default
Not passed yetWrite greet(name, greeting="Assalamu alaikum") returning "greeting, name!". Print greet("Mim") and then greet("Rafi", "Hello") — two lines.
def greet(name, greeting="Assalamu alaikum"):
# return the combined string
print(greet("Mim"))
print(greet("Rafi", "Hello"))
Lab 4: Sum any number of bills
Not passed yetWrite total(*bills) that accepts ANY count of amounts and returns their sum. Print total(120, 80.5, 60).
def total(*bills):
# return the sum
print(total(120, 80.5, 60))
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.)