26 min read
Functions
Define functions with def, pass in parameters, return results, and call them — the modules of a Python program.
Why Functions?
A function is a named block of code that does one job. You define it once with def, then call it whenever you need it. You have already used built-in functions: print(), input(), int(), round(). Now you will write your own — this is the modular programming from the Introduction to Programming course.
Defining and Calling
A function with no parametersPython
def show_header(): print("PERERA CORNER MART") print("Negombo · Open 7 am to 10 pm") show_header()print("Thank you for shopping!")show_header()Expected output
PERERA CORNER MART Negombo · Open 7 am to 10 pm Thank you for shopping! PERERA CORNER MART Negombo · Open 7 am to 10 pm
- def + name + ( ) + colon starts the definition. The body is indented.
- Defining a function does not run it. It runs when it is called:
show_header(). - A function must be defined before it is called in the program.
Parameters and Arguments
Passing values inPython
def line_total(price, quantity): print(f"{quantity} x {price} = {price * quantity}") line_total(280, 5)line_total(452.5, 2)Expected output
5 x 280 = 1400 2 x 452.5 = 905.0
| Key words | ||
|---|---|---|
Returning a Value
return sends a result backPython
def apply_discount(total): if total > 5000: return total * 0.9 return total bill = 7200to_pay = apply_discount(bill)print(f"To pay: LKR {to_pay:,.2f}")print(apply_discount(3000))Expected output
To pay: LKR 6,480.00 3000
return ends the function and sends a value back to where it was called — so the result can be stored (to_pay = …), printed or used in a calculation. A function without return gives back None.
print vs return: print only shows a value on the screen. return hands it back to the program to use.
Functions in Flowcharts
In a flowchart, a call to a function is drawn as a predefined process — a rectangle with double sides. The function itself gets its own small flowchart starting with its name instead of "Start".
The flowchart of the apply_discount function
Read this flowchart as text
- Terminator: apply_discount(total) (then → total > 5000?)
- Decision: total > 5000? (Yes → result = total × 0.9; No → result = total)
- Process: result = total (then → Return result)
- Process: result = total × 0.9 (then → Return result)
- Terminator: Return result
Local Variables
Variables created inside a function are local: they exist only while the function runs. Pass values in as parameters and send results out with return, rather than relying on variables outside the function.
Practice
More lessons in Python Programming · Next: Putting It Together: the Shop Till · Previous: while Loops
