Imagine writing the same 10 lines of code over and over. π΄ Boring, right? A function lets you save a block of code under a name, then run it whenever you want β just like pressing a button on a machine! ποΈ And modules let you use code other people already wrote (or split your own code into tidy files). This is how real programmers build big things.
A function is created with the keyword def, followed by a name,
parentheses (), and a colon. The body is indented. To run it,
you βcallβ it by writing its name with parentheses.
def.
2οΈβ£ Call it by typing its name. Defining it alone does nothing!
Functions get more powerful when you pass them parameters β values inside the parentheses. Think of them as the ingredients you feed the machine.
def add(a, b):
and call it like add(3, 5).
print() just shows something on the screen. But return
sends a value back to whoever called the function β so you can store it in a variable,
do maths with it, or use it again. This is how functions become building blocks.
return ends the function immediately. Any code after it inside the function wonβt run.
You can give a parameter a default value so itβs optional. You can also pass arguments by name (keyword) instead of just position β great for clarity and skipping optional ones.
def f(a=1, b): β thatβs an error.
Variables created inside a function only exist there β this is called local scope. Variables outside are global. This keeps functions neat and prevents accidents.
return results out.
Avoid changing global variables from inside functions β it gets confusing fast!
A module is a file full of Python code β functions, variables, everything.
Python comes with loads of built-in modules, and you can use them with import.
This is modularity: building big programs from small pieces.
| Import style | How you use it |
|---|---|
import math | math.sqrt(16) |
from math import sqrt | sqrt(16) |
import random as rnd | rnd.randint(1, 6) |
mytools.py with functions,
then in another file use import mytools β instant reuse across projects!
Hereβs a small program that uses functions, parameters, defaults, returns, and a module β a mini dice game!
dice_game.py and run it a few times.
Change the default to sides=20 and watch the rolls get bigger!
Create a file called toolkit.py with three useful functions, then call them in the same file. Each should take parameters and return a value:
area_rectangle(length, width) β returns the area.celsius_to_fahrenheit(c) β returns the temperature in Β°F (formula: c * 9/5 + 32).is_even(number) β returns True if even, False if odd.
π Bonus: add a default parameter β e.g. area_rectangle(length, width=10) β
so you can call it with just one value.
def creates a function, return sends a value back,
and import grabs tools from modules. Small functions = happy coders!