Lesson 1 of 12 · 38 min · Grades 9–12
Functions — reusable recipe cards
The chemistry lab keeps printed cards: “To make 100 ml saline, mix …”. Anyone can follow the card with different amounts. A function is that card: a name, inputs (parameters), a body, and often a return value. Without functions, programs become copy-paste novels. With them, you fix a formula in one place.
Lab recipe cards
Functions are reusable procedures.
You will be able to
- ✓ Define a function with def and a colon
- ✓ Pass arguments and use return
- ✓ Call the same function with different inputs
def names a procedure
def greet(name): starts a function. The indented block is the recipe. greet is the name you will call later. name is a parameter — a labelled bag that exists only while the function runs.
Calling greet("Diya") puts "Diya" into name and runs the body. Calling greet("Kabir") reuses the same body. That is the entire point: one definition, many uses.
return vs print
print shows a human. return hands a value back to the caller so the rest of the program can store it, print it, or send it into another function. A GST helper should return the amount; the cashier program decides whether to print a receipt.
If you only print inside a function, you cannot add two results together. return 118 lets you write bill = add_gst(100) + delivery.
Return a number, print outside
def square(n):
return n * n
print("Area of 5x5 tile", square(5))
Parameters are local
A parameter does not overwrite a variable of the same name outside the function in the way beginners fear — think of it as a new bag on a new desk. When the function ends, the desk is cleared.
Name parameters after meaning: amount, days, width. Avoid f(x, y, z) unless you are writing pure maths. Future you will thank present you.
Words that matter
- Parameter
- A named input listed in the def line.
- Argument
- The actual value you pass when calling.
- return
- Sends a value back to the caller.
Common mistakes
Avoid: Using print instead of return when the caller needs a number.
Do this: return the value; let the caller print.
Avoid: Forgetting the colon after def greet(name).
Do this: def greet(name): then indent the body.
Example program — Rectangle area for art class
Call area twice. One definition, two posters.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — GST helper
Write add_gst(amount) that returns amount * 118 / 100. Print add_gst(100) so 118 appears.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.