Skip to content

Module 9 · Functions — topic 1 of 19

Functions

What a function is, why programs are built from them, the difference between built-in and user-defined functions, and how a function call transfers control and returns a result.

Beginner 10 min read·Lesson 126 of 306 in Python Programming

Learning objectives

  • Explain what a function is and why it is useful
  • Distinguish built-in functions from functions you write
  • Describe what happens when a function is called

Definition

A function is a named, reusable block of code that performs one task. It may receive input values (arguments), and it can send a result back to the code that called it with return.

Introduction

You have already used many functions: print(), len(), input(), round(), sorted(). Each one hides a piece of work behind a name. You call it, give it what it needs, and get a result back, without caring how it works inside.

Python lets you write your own functions in exactly the same way. Once a calculation or task has a name, you can reuse it anywhere, test it on its own and change it in one place.

Why it matters

Real programs are thousands of lines long. Without functions they would be one enormous script that nobody could understand. Functions break a problem into small named pieces, each easy to read and to check.

Functions also remove duplication. If the same five lines appear in three places, a bug must be fixed three times; in a function it is fixed once.

Detailed explanation

Built-in functions come with Python and are always available. User-defined functions are the ones you write with the def keyword. Library functions come from modules you import, such as math.sqrt.

Calling a function means writing its name followed by parentheses, with any arguments inside: area(3, 4). Python pauses the current code, runs the function body with those values, and then continues from where it left off.

A function can return a value with return; the call expression then evaluates to that value, so you can store it, print it or pass it to another function. A function without a return statement returns None.

Good functions do one thing, have a descriptive name (usually a verb such as calculate_total or is_valid_email), and depend only on their inputs whenever possible. Such functions are easy to test and reuse.

Thinking in functions is a form of abstraction: once average() works, you can use it while thinking only about what it does, not how.

Syntax

Python
def function_name(parameter1, parameter2):
"""What the function does."""
# body
return result
value = function_name(argument1, argument2)
  • def starts a function definition.
  • The body is indented.
  • Calling the function runs the body.

Code examples

Built-in functions

Python
marks = [72, 95, 58]
print(len(marks), max(marks), sum(marks))
print(round(sum(marks) / len(marks), 2))
Output
3 95 225
75.0

Your first function

Python
def greet(name):
return "Hello, " + name + "!"
print(greet("Asha"))
print(greet("Ravi"))
Output
Hello, Asha!
Hello, Ravi!

More examples

Replacing repeated code with a function

Python
def report(name, marks):
average = sum(marks) / len(marks)
status = "pass" if min(marks) >= 35 else "fail"
return f"{name}: average {average:.1f}, {status}"
print(report("Asha", [92, 88, 95]))
print(report("Ravi", [67, 30, 80]))
print(report("Meera", [85, 91, 78]))
Output
Asha: average 91.7, pass
Ravi: average 59.0, fail
Meera: average 84.7, pass

Step-by-step explanation

  • def report(name, marks): defines a function with two parameters.
  • Inside, average and status are computed from the parameters.
  • return sends a formatted string back to the caller.
  • Each print(report(...)) call runs the body with different arguments and prints the returned string.

Expected output

Running “Replacing repeated code with a function” prints exactly:

TextOutput
Asha: average 91.7, pass
Ravi: average 59.0, fail
Meera: average 84.7, pass

Practical applications

  • A web app has functions such as login(), add_to_cart() and send_invoice().
  • Data scripts define clean_row() and summarise() and apply them to every record.
  • Libraries like math and statistics are collections of well-tested functions.

Best practices

  • Give each function one clear job and a verb name.
  • Prefer returning results over printing inside functions.
  • Keep functions short enough to read at a glance.

Common mistakes

Defining but never calling

Avoid

def greet():
print("Hi")
# nothing happens

Prefer

def greet():
print("Hi")
greet()

A def only creates the function. The body runs when you call it.

Printing instead of returning

Avoid

def square(x):
print(x * x)
y = square(4) + 1 # TypeError: None + 1

Prefer

def square(x):
return x * x
y = square(4) + 1

print shows a value but the function still returns None; return makes the value available to the caller.

Important notes

  • Functions are objects in Python: you can store them in variables and pass them to other functions (see First-class functions).

Key takeaways

  • A function is a named, reusable block of code.
  • Calling it runs the body with the given arguments.
  • return sends a value back; without it the result is None.

Try it yourself

  1. 1
    Write a function celsius_to_fahrenheit(c) and print the result for 0, 37 and 100.
  2. 2
    Write is_even(n) that returns True or False, and use it in a loop over 1 to 10.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

15 questions cover the “Functions” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module