Comprehensive Guide to Python Functions with Examples

Comprehensive Guide to Python Functions with Examples

Functions are one of the fundamental building blocks in Python programming. They allow you to organize your code into reusable blocks that perform specific tasks. In this guide, we will dive deep into how to create and use functions in Python, explore different types of arguments, and understand the difference between printing and returning values from functions.


1. What is a Function?

A function is a named block of code that performs a specific task. Once a function is defined, you can call (execute) it any number of times from different parts of your program. Functions help you avoid repetition, improve code readability, and organize your logic effectively.

Basic Syntax


def function_name(parameters):
    # function body (code)
    return value  # optional

Here:

  • def keyword is used to declare a function.
  • function_name is the name you give your function.
  • parameters are variables passed to the function to accept inputs (can be empty).
  • return is used to send a result back to the caller (optional).

Example 1: Simple Function Without Parameters


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

greet()

Output:


Hello, welcome to Python!

Note: This function simply prints a message and does not return any value.


2. Parameters and Arguments

Functions can take inputs to perform tasks based on those inputs. These inputs are called parameters inside the function definition and arguments when you call the function.

Example 2: Function with a Parameter


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

greet("Ayush")
greet("Arun")

Output:


Hello, Ayush
Hello, Arun

Important: The order and number of arguments must match the parameters defined unless you use special types of arguments (explained below).


3. Different Types of Function Arguments

3.1 Positional Arguments

These are the most common arguments where values are passed in the same order as parameters.


def full_name(first, last):
    print("Full Name:", first, last)

full_name("John", "Doe")

Output:


Full Name: John Doe

3.2 Keyword Arguments

You can specify arguments by the parameter name, so the order doesn't matter.


full_name(last="Doe", first="John")

Output:


Full Name: John Doe

3.3 Default Arguments

Assign default values to parameters so if no argument is passed, the default is used.


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

greet()
greet("Arun")

Output:


Hello Guest
Hello Arun

3.4 Variable-Length Arguments

When you don’t know how many arguments might be passed, use *args and **kwargs.

  • *args — collects extra positional arguments into a tuple.
  • **kwargs — collects extra keyword arguments into a dictionary.

Example using *args


def add_numbers(*args):
    total = 0
    for num in args:
        total += num
    print("Sum is", total)

add_numbers(5, 10, 15)

Output:


Sum is 30

Example using **kwargs


def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Ayush", age=18, city="Delhi")

Output:


name: Ayush
age: 18
city: Delhi

4. Printing vs Returning Values

Understanding the difference between print() and return is crucial for writing effective functions.

4.1 Printing inside Functions

When you use print() inside a function, it outputs the data immediately to the console but the function itself returns None.


def show():
    print("Hello from function")

result = show()
print("Returned:", result)

Output:


Hello from function
Returned: None

4.2 Returning Values from Functions

return passes a value back to the caller and ends the function execution.


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

result = add(10, 5)
print("Sum is", result)

Output:


Sum is 15

Note: Returned values can be stored, manipulated, or used in expressions later, unlike printed values.


5. How to Return Multiple Values

You can return multiple values separated by commas — Python packs them into a tuple.


def get_name_and_age():
    name = "Ayush"
    age = 18
    return name, age

person_name, person_age = get_name_and_age()
print(person_name)
print(person_age)

Output:


Ayush
18

6. Complete Function Example: Simple Calculator


def calculator(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "sub":
        return a - b
    elif operation == "mul":
        return a * b
    elif operation == "div":
        if b != 0:
            return a / b
        else:
            return "Cannot divide by zero"
    else:
        return "Invalid operation"

print(calculator(10, 5, "add"))  # 15
print(calculator(10, 5, "sub"))  # 5
print(calculator(10, 5, "div"))  # 2.0
print(calculator(10, 0, "div"))  # Cannot divide by zero
print(calculator(10, 5, "xyz"))  # Invalid operation

Output:


15
5
2.0
Cannot divide by zero
Invalid operation

7. Important Notes and Best Practices

  • Use meaningful function names: Choose names that clearly describe what the function does.
  • Keep functions small: Each function should do one specific task.
  • Use return for reusable results: If you want to reuse the output later, return it instead of printing.
  • Use default arguments to make your functions flexible.
  • Use *args and **kwargs for functions with variable input.
  • Always test your functions with different inputs to avoid unexpected errors.

Summary Table

Term Description
Function Reusable block of code performing a specific task.
Parameter Variable in function definition to accept input.
Argument Value passed to function parameter during call.
Return Sends a value back to the caller and ends function.
Print Outputs data immediately but does not send back value.
*args Variable number of positional arguments packed into tuple.
**kwargs Variable number of keyword arguments packed into dict.

📚 Practice Questions:


📚 Related Topics:


📌 Bookmark this blog or follow for updates!

Python Logo

👍 Liked this post? Share it with friends or leave a comment below!

Previous Post Next Post

Contact Form