As your programs grow, you'll notice that you keep writing the same lines of code again and again. Printing a welcome message, calculating a total, checking if a number is even... copying and pasting this code everywhere quickly becomes messy.
Python solves this with functions. You write a piece of code once, give it a name, and then use that name whenever you need the code to run.
Think of a function like a recipe for masala chai. You write the steps down once. Whenever you want chai, you don't rethink every step, you just say "make chai" and follow the recipe.
What is a Function?
A function is a named block of code that performs a specific task. It runs only when it is called.
You have already been using functions since your very first program:
print("Hello") # print() is a function
name = input() # input() is a function
length = len("Python") # len() is a functionThese are built-in functions, which Python gives you for free. In this chapter, you'll learn to create your own functions, called user-defined functions.
Defining a Function
We create a function using the def keyword:
def function_name():
# body of the function
# (indented code)Let's break this down:
def greet ( ) :
| | | |
| | | +-- colon starts the function body
| | +------ parentheses (parameters go here)
| +------------ name of the function
+------------------ keyword that means "define"The body of the function must be indented, just like the body of an if statement or a loop.
Your First Function
def greet():
print("Hello!")
print("Welcome to CS Learning Portal.")If you run this code, nothing is printed. That surprises many beginners.
Defining a function only creates it. Python remembers the function but does not run its body yet.
Calling a Function
To run the code inside a function, you call it by writing its name followed by parentheses:
def greet():
print("Hello!")
print("Welcome to CS Learning Portal.")
greet()
greet()Output:
Hello!
Welcome to CS Learning Portal.
Hello!
Welcome to CS Learning Portal.We wrote the two print() lines only once, but they ran twice, because we called greet() twice.
How Python Runs a Function Call
print("Start")
def greet():
print("Inside greet")
greet()
print("End")Output:
Start
Inside greet
EndHere is what happens step by step:
Python prints
Start.Python reads the
defblock and remembers the function. Nothing is printed.greet()is called, so Python jumps into the function and runs its body.When the body finishes, Python comes back to the line after the call and prints
End.
Functions with Parameters
Our greet() function always prints the same thing. To make it more useful, we can pass it some information using a parameter:
def greet(name):
print(f"Hello, {name}!")
greet("Riya")
greet("Arjun")Output:
Hello, Riya!
Hello, Arjun!Here, name is a parameter. It works like a variable that receives whatever value we pass when calling the function.
A function can have more than one parameter, separated by commas:
def add(a, b):
print(a + b)
add(5, 3)
add(10, 20)Output:
8
30There's a lot more to parameters, such as default values and keyword arguments. We'll cover them in detail in the next chapter, Function Arguments in Python.
Getting a Result Back with return
So far, our functions only print things. Often, we want a function to calculate something and give the result back so we can use it later. For that, we use return:
def square(number):
return number * number
result = square(4)
print(result)
print(square(5) + square(2))Output:
16
29square(4) sends back 16, which we store in result. Because the function returns a value, we can even use the calls directly inside an expression.
We'll explore return properly, including the difference between print and return, in the chapter Return Values & Variable Scope in Python.
Functions Calling Other Functions
A function can call another function. This lets you build bigger tasks out of smaller ones:
def print_line():
print("-" * 20)
def print_report(name, marks):
print_line()
print(f"Student: {name}")
print(f"Marks : {marks}")
print_line()
print_report("Meera", 92)Output:
--------------------
Student: Meera
Marks : 92
--------------------Docstrings: Documenting Your Function
A docstring is a string written as the very first statement inside a function body. It describes what the function does.
def is_even(number):
"""Return True if number is even, otherwise False."""
return number % 2 == 0
print(is_even(10))
print(is_even.__doc__)Output:
True
Return True if number is even, otherwise False.Docstrings are usually written with triple quotes. Tools like help(is_even) and code editors show them to anyone using your function, so it's a good habit to write one.
Empty Functions with pass
A function body cannot be empty. If you want to create a function now and write its code later, use pass:
def calculate_tax():
pass # TODO: write this laterpass does nothing. It simply acts as a placeholder so the code is still valid.
Why Use Functions?
Benefit | What it means |
|---|---|
Reusability | Write the code once, call it as many times as needed |
Readability | A name like |
Easy changes | Fix a bug in one place instead of in every copy |
Easier testing | You can test each small function on its own |
Organisation | Big programs are broken into small, manageable pieces |
This idea is often called DRY: Don't Repeat Yourself.
Naming Functions
Function names follow the same rules as variable names. By convention (PEP 8), Python uses lowercase words separated by underscores (snake_case). Since functions do something, starting with a verb works well:
def calculate_average(): # good
pass
def send_email(): # good
pass
def CalculateAverage(): # works, but not Python style
passCommon Mistakes
1. Calling a function before defining it
say_hi()
def say_hi():
print("Hi!")Output:
NameError: name 'say_hi' is not definedPython runs code from top to bottom. When it reaches say_hi(), the function doesn't exist yet. Always define a function before the line that calls it.
2. Forgetting the parentheses
def greet():
print("Hello!")
greet # does NOT call the function
greet() # calls the functionWriting just greet refers to the function object itself, it does not run it. If you print it, you'll see something like <function greet at 0x...> instead of Hello!.
3. Wrong indentation
def greet():
print("Hello!") # IndentationError: expected an indented block after function definitionEvery line of the function body must be indented (4 spaces is the standard).
Summary
A function is a named, reusable block of code.
Create a function with
def name():and an indented body.Defining a function does not run it. You must call it using
name().Parameters let you pass data into a function.
returnsends a result back to the caller.Use docstrings to describe your functions and
passas a placeholder.
Write it once, name it well, call it whenever you need it.
In the next chapter, we'll look at the different ways to pass values into functions using arguments.