DEV Community

Adhi sankar
Adhi sankar

Posted on

Functions in Python: A Beginner's Guide with Examples

What is a Function?

A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you can write it once inside a function and call it whenever needed.

Example

def greet():
    print("Hello, Welcome to Python!")

greet()
Enter fullscreen mode Exit fullscreen mode

Output

Hello, Welcome to Python!
Enter fullscreen mode Exit fullscreen mode

In this example:

  • def is the keyword used to define a function.
  • greet is the function name.
  • Parentheses () hold parameters if needed.
  • The indented block contains the function body.
  • greet() calls the function.

Why Use Functions?

Functions provide several advantages:

  • Reduce code duplication.
  • Improve code readability.
  • Make programs easier to maintain.
  • Allow code reuse.
  • Simplify debugging and testing.

Syntax of a Function

def function_name(parameters):
    # Function body
    return value
Enter fullscreen mode Exit fullscreen mode

Function Without Parameters

A function can work without taking any input.

def say_hello():
    print("Hello World!")

say_hello()
Enter fullscreen mode Exit fullscreen mode

Output

Hello World!
Enter fullscreen mode Exit fullscreen mode

Function With Parameters

Parameters allow you to pass information into a function.

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

greet("Adhi")
Enter fullscreen mode Exit fullscreen mode

Output

Hello Adhi
Enter fullscreen mode Exit fullscreen mode

Function With Multiple Parameters

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

add(10, 20)
Enter fullscreen mode Exit fullscreen mode

Output

30
Enter fullscreen mode Exit fullscreen mode

Returning Values

The return statement sends a value back to the caller.

def square(number):
    return number * number

result = square(5)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output

25
Enter fullscreen mode Exit fullscreen mode

Difference Between print() and return

Using print()

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

add(5, 3)
Enter fullscreen mode Exit fullscreen mode

Output

8
Enter fullscreen mode Exit fullscreen mode

The value is displayed but cannot be reused.

Using return

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

result = add(5, 3)
print(result * 2)
Enter fullscreen mode Exit fullscreen mode

Output

16
Enter fullscreen mode Exit fullscreen mode

The returned value can be stored and used later.


Default Parameters

You can assign default values to parameters.

def greet(name="Guest"):
    print("Hello", name)

greet()
greet("Adhi")
Enter fullscreen mode Exit fullscreen mode

Output

Hello Guest
Hello Adhi
Enter fullscreen mode Exit fullscreen mode

Keyword Arguments

You can pass arguments using parameter names.

def student(name, age):
    print(name, age)

student(age=21, name="Adhi")
Enter fullscreen mode Exit fullscreen mode

Output

Adhi 21
Enter fullscreen mode Exit fullscreen mode

Arbitrary Arguments (*args)

Use *args when you don't know how many arguments will be passed.

def numbers(*values):
    print(values)

numbers(10, 20, 30, 40)
Enter fullscreen mode Exit fullscreen mode

Output

(10, 20, 30, 40)
Enter fullscreen mode Exit fullscreen mode

Arbitrary Keyword Arguments (**kwargs)

Use **kwargs to accept multiple keyword arguments.

def student(**details):
    print(details)

student(name="Adhi", age=21, city="Chennai")
Enter fullscreen mode Exit fullscreen mode

Output

{'name': 'Adhi', 'age': 21, 'city': 'Chennai'}
Enter fullscreen mode Exit fullscreen mode

Local Variables

Variables declared inside a function exist only within that function.

def demo():
    message = "Python"
    print(message)

demo()
Enter fullscreen mode Exit fullscreen mode

Global Variables

Variables declared outside a function can be accessed inside it.

language = "Python"

def display():
    print(language)

display()
Enter fullscreen mode Exit fullscreen mode

Output

Python
Enter fullscreen mode Exit fullscreen mode

Lambda Functions

A lambda function is a small anonymous function written in a single line.

square = lambda x: x * x

print(square(6))
Enter fullscreen mode Exit fullscreen mode

Output

36
Enter fullscreen mode Exit fullscreen mode

Recursive Functions

A recursive function calls itself.

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
Enter fullscreen mode Exit fullscreen mode

Output

120
Enter fullscreen mode Exit fullscreen mode

Built-in Functions

Python provides many built-in functions.

Examples include:

print(len("Python"))

print(max(5, 10, 15))

print(min(5, 10, 15))

print(sum([1, 2, 3, 4]))
Enter fullscreen mode Exit fullscreen mode

Output

6
15
5
10
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Use meaningful function names.
  • Keep functions short and focused.
  • Avoid repeating code.
  • Use comments when necessary.
  • Return values instead of printing when possible.

Common Mistakes

Forgetting Parentheses

greet
Enter fullscreen mode Exit fullscreen mode

Correct:

greet()
Enter fullscreen mode Exit fullscreen mode

Missing Return Statement

def add(a, b):
    a + b
Enter fullscreen mode Exit fullscreen mode

Correct:

def add(a, b):
    return a + b
Enter fullscreen mode Exit fullscreen mode

Incorrect Indentation

def hello():
print("Hello")
Enter fullscreen mode Exit fullscreen mode

Correct:

def hello():
    print("Hello")
Enter fullscreen mode Exit fullscreen mode

Real-World Example

def calculate_total(price, quantity):
    return price * quantity

product_price = 250
quantity = 4

total = calculate_total(product_price, quantity)

print("Total Amount:", total)
Enter fullscreen mode Exit fullscreen mode

Output

Total Amount: 1000
Enter fullscreen mode Exit fullscreen mode

Summary

Functions are one of Python's most powerful features. They make programs modular, reusable, and easier to maintain. Whether you're writing a small script or a large application, using functions effectively will improve the quality of your code.

Key Takeaways

  • Functions are reusable blocks of code.
  • Use def to define a function.
  • Parameters allow functions to accept input.
  • return sends values back to the caller.
  • Python supports default arguments, keyword arguments, *args, and **kwargs.
  • Lambda functions are useful for short operations.
  • Recursive functions solve problems by calling themselves.
  • Good functions are simple, reusable, and easy to understand.

Top comments (0)