Functions · Lesson 22 of 39
Defining and Calling Functions
A function is a named, reusable block of code. You have used many already – print(), len(), sorted(). Now you will write your own. Functions are how real programs stay organised: each one does a single job, has a clear name and can be tested on its own.
In this lesson
- Defining a function with
def - Parameters, arguments and
return - The difference between printing and returning
- Docstrings and good function design
Your first function
def greet(name):
"""Return a friendly greeting for name."""
return f"Hello, {name}! Welcome to LearnFrenzy."
message = greet("Isha")
print(message)
print(greet("Omar"))
Hello, Isha! Welcome to LearnFrenzy. Hello, Omar! Welcome to LearnFrenzy.
defstarts the definition;greetis the name;nameis a parameter – a placeholder for the input.- The indented block is the body. It does not run when Python reads the
def, only when the function is called. "Isha"is the argument – the actual value passed in the call.returnsends a value back to whoever called the function.
What happens during a call
message = greet("Isha")
- Jump into the functionname = "Isha" (a new local variable)
- Run the bodybuild the greeting text
- return the valuethe function ends immediately
- Back at the callmessage = "Hello, Isha! …"
Python keeps track of active calls on the call stack. Each call gets its own fresh set of local variables, which disappear when the call returns.
Several parameters and return values
def bill_total(price, quantity, gst_rate):
subtotal = price * quantity
tax = subtotal * gst_rate
return subtotal + tax
print(bill_total(250, 4, 0.18))
print(bill_total(99, 1, 0.05))
1180.0 103.95
return also ends the function early, which makes guard clauses easy:
def safe_divide(a, b):
if b == 0:
return None # stop here
return a / b
print(safe_divide(10, 4))
print(safe_divide(10, 0))
2.5 None
print or return?
This is the most common confusion for beginners. print shows text on the screen for a human. return hands a value back to the program so it can be used further.
def area_print(w, h):
print(w * h)
def area_return(w, h):
return w * h
a = area_print(3, 4) # shows 12, but gives back None
b = area_return(3, 4) # shows nothing, gives back 12
print(a, b)
print(area_return(3, 4) + area_return(2, 5))
12 None 12 22
Common mistake: a function without return
If a function has no return (or a bare return), it returns None. If you see an unexpected None or TypeError: unsupported operand type(s) … 'NoneType', check that your function returns its result instead of printing it.
Docstrings
The string right under def is a docstring. Editors show it on hover, and help() prints it. Describe what the function does, its inputs and its result:
def bmi(weight_kg, height_m):
"""Return the body-mass index.
weight_kg: body weight in kilograms
height_m: height in metres
"""
return round(weight_kg / height_m ** 2, 1)
print(bmi(70, 1.75))
print(bmi.__doc__.splitlines()[0])
22.9 Return the body-mass index.
Functions calling functions
Small functions combine into bigger ones. Each piece stays easy to read and test:
def average(numbers):
return sum(numbers) / len(numbers)
def grade(score):
if score >= 85:
return "A"
if score >= 70:
return "B"
return "C"
def report(name, marks):
avg = average(marks)
return f"{name}: average {avg:.1f}, grade {grade(avg)}"
print(report("Nikhil", [88, 92, 79]))
print(report("Pooja", [65, 71, 70]))
Nikhil: average 86.3, grade A Pooja: average 68.7, grade C
Functions are values
In Python a function is an object like any other: you can store it in a variable, put it in a list, or pass it to another function. You did this already with sorted(words, key=len).
def shout(text):
return text.upper() + "!"
def whisper(text):
return text.lower() + "..."
for style in [shout, whisper]:
print(style("Hello"))
HELLO! hello...
Good function design
- One job per function. If the name needs "and", split it.
- Verb names that say what it does:
calculate_tax,send_email,is_valid. - Return results rather than printing them, so callers decide what to do.
- Keep it short – most good functions fit on one screen.
Practice
Try it yourself
Write
is_even(n)that returns True or False.Show solution
def is_even(n): return n % 2 == 0 print(is_even(10), is_even(7))True False
Write
count_vowels(text)and use it on "Functions are fun".Show solution
def count_vowels(text): return sum(1 for ch in text.lower() if ch in "aeiou") print(count_vowels("Functions are fun"))6
Write
fizzbuzz(n)that returns "Fizz" for multiples of 3, "Buzz" for 5, "FizzBuzz" for both, otherwise the number as text. Print results for 1–15.Show solution
def fizzbuzz(n): if n % 15 == 0: return "FizzBuzz" if n % 3 == 0: return "Fizz" if n % 5 == 0: return "Buzz" return str(n) print(" ".join(fizzbuzz(i) for i in range(1, 16)))1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Quick check
Parameter or argument: which one is in the def line?
The parameter. Arguments are the values you pass when calling.
What does a function return if it has no return statement?
None.
Does the body of a function run when Python reads def?
No. def only creates the function; the body runs each time it is called.
Summary
def name(params):defines a function; calling it runs the body.returnsends a value back and ends the call; no return meansNone.- Return results instead of printing them; document with a docstring.
- Functions are objects – you can pass them around like data.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.