Defining and Calling Functions
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Functions are reusable blocks of code that perform a specific task. They prevent repetition (DRY: Don't Repeat Yourself) and make software modular and testable.
Defining and calling a function
Function is a named block of code that does one job. You write it once with def, then run it as many times as you like by calling its name.
Use the def keyword followed by the function name, parentheses (), and a colon. Indent the function body by 4 spaces.
def greet(user_name): """Display a personalized welcome greeting.""" print(f"Hello, {user_name}!")
greet("Rohan")Example 1 · One job, many calls
def show_total(price, quantity): print(f"Total: {price * quantity}")
show_total(250, 2)show_total(99, 5)Total: 500 Total: 495
What this code does
defwrites the steps once. Each call runs them again with new values.priceandquantityhold 250 and 2 on the first call, then 99 and 5 on the second.
The triple-quoted string immediately below the def line is the docstring, accessible via help(greet) or IDE tooltips.
Returning values with return
Return value is the result a function sends back to the code that called it, using return. The call then stands for that value.
Use return to send a calculated result back to the caller. Executing return terminates the function immediately.
def calculate_area(length, width): return length * width
area = calculate_area(12, 5)print(f"Area: {area}")Example 2 · Even or odd check
def is_even(number): """Return True if number is even, False otherwise.""" return number % 2 == 0
print(is_even(10))print(is_even(7))True False
What this code does
is_even(10)evaluates10 % 2 == 0, returningTrue.is_even(7)evaluates7 % 2 == 0, returningFalse.
Example 3 · Result goes back to the caller
def add_tax(price): return price + price * 18 // 100
total = add_tax(200) + add_tax(100)print(total)354
What this code does
add_tax(200)returns 236 andadd_tax(100)returns 118.- Because the function returns values, the caller can add them: 236 + 118 = 354.
The function returns 60, which is assigned to the variable area.
Functions without return yield None
None is the special value Python uses for "no value". A function that ends without a return statement gives back None.
If a function finishes without encountering a return statement, Python automatically returns None.
def log_action(msg): print(f"[LOG] {msg}")
result = log_action("Task complete")print(f"Return value: {result}")Example 4 · The value of a call with no return
def log_order(order_id): print(f"Order {order_id} saved")
result = log_order(101)print(result)print(result is None)Order 101 saved None True
What this code does
- The function prints one line but sends nothing back.
- So
resultisNone, whichresult is Noneconfirms.
Even though log_action printed text to the screen, its return value is None.
Next step
Check your understanding
9 quick questions