Home → Lessons → Functions in Python

Functions in Python

Learn how to create reusable blocks of code using functions in Python.

Lesson 08 Beginner 20 min

What are Functions?

A function is a reusable block of code that performs a specific task.

Functions help make programs easier to understand, reuse and maintain.

Basic Syntax:

def function_name(): # code

1. Creating a Function

In Python, we use the def keyword to define a function.

Example
def greet():
    print("Hello, PyStep!")

Here, greet is the name of the function.

2. Calling a Function

A function runs when we call it using its name followed by parentheses.

Example
def greet():
    print("Hello, PyStep!")

greet()
Output:
Hello, PyStep!

3. Function Parameters

Parameters allow us to pass information to a function.

Example
def greet(name):
    print("Hello", name)

greet("Sudhanshu")
Output:
Hello Sudhanshu

4. Multiple Parameters

A function can have more than one parameter.

def add(a, b):
    print(a + b)

add(10, 20)
Output:
30

5. return Statement

The return statement sends a result back from a function.

Example
def add(a, b):
    return a + b

result = add(10, 20)

print(result)
Output:
30

6. Practical Example

Functions can be used to calculate the square of a number.

Square Function
def square(number):
    return number * number

answer = square(5)

print("Square =", answer)
Output:
Square = 25

7. Advantages of Functions

Reusability

Write code once and use it multiple times.

Easy to Understand

Functions divide a large program into smaller parts.

Easy Maintenance

Changes can be made in one function instead of repeating code.

Remember:

def is used to define a function.

Parameters receive values, while return sends a result back.

Quick Quiz

Which keyword is used to define a function in Python?

Finished this lesson?