What are Functions in Python?

Subh Singh
Invent the Future

A function is a reusable block of code that is defined using the def keyword in Python. The def keyword is a reserved keyword that Python recognizes to define a function.

The main purpose of a function is to group a piece of code into a single reusable block. Instead of writing the same code again and again, you can write it once inside a function and call it whenever you need it. It reduces code duplication by allowing you to write the same code only once. As a result, the program becomes shorter, easier to read, and easier to maintain.

Example:

Without using a function:

print(2 + 2)
print(2 + 2)
print(2 + 2)
print(2 + 2)
print(2 + 2)
print(2 + 2)
print(2 + 2)
print(2 + 2)
print(2 + 2)
print(2 + 2)

Here, the same code repeats 10 times.

Using a function:

def print_four():
    print(2 + 2)

for i in range(10):
    print_four()

Here, the code is written only once inside the function and called 10 times.