Chapter 5 — Python Functions & Modules
📚 Chapter Overview
Organization is the key to scale. In this chapter, you will learn how to wrap logic into reusable Functions, pass data using Arguments, and organize your code into external Modules.
Learning Objectives:
- Define and Call functions using
def. - Master Positional vs Keyword Arguments.
- Import and use Standard Library modules (math, random).
5.1 Function Basics
Part 1 — Definition
A Function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Functions help in breaking a large program into small, manageable parts.
Part 2 — Syntax
def my_function(param):
# code
return result
my_function("val")
Part 3 — Example
Problem: Create a function that greets the user with their name.
def greet(name):
print(f"Hello, {name}!")
greet("Ali")
Part 4 — Video
Video: Coming Soon
5.2 Modules and Imports
Part 1 — Definition
A Module is a file containing Python definitions and statements. You can use any Python source file as a module by executing an import statement in some other Python source file. This allows you to logically organize your Python code.
Part 2 — Syntax
import math
print(math.sqrt(16))
from random import randint
print(randint(1, 10))
Part 3 — Example
Problem: Generate a random dice roll.
import random
def roll_dice():
return random.randint(1, 6)
print(f"You rolled: {roll_dice()}")
Observation: Using from module import function allows you to call the function directly without the module prefix.
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Geometry Helper" module.
Requirements
- Create functions for
area_circle(r)andarea_square(s). - Use the
mathmodule for the value of Pi. - Allow the user to pick a shape and provide dimensions.
Step-by-Step Process
- Define the functions with return statements.
- Import
math.pi. - Use a loop to allow multiple calculations until the user quits.
Expected Deliverables
geometry.pysource file.