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:

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.

script.py
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.

script.py
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

Step-by-Step Process

  1. Define the functions with return statements.
  2. Import math.pi.
  3. Use a loop to allow multiple calculations until the user quits.

Expected Deliverables

Solve in Compiler