EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Python

Python Functions

Computer Science / Python tutorial chapter - Published 2025-12-17 - Python

A function in Python is a block of code designed to perform a specific task. By grouping repetitive tasks into functions, you can reuse the same code for different inputs, improving both efficiency and maintainability.

Benefits of Using Functions

  • Improves Code Readability: By abstracting complex tasks into named functions, the main code becomes cleaner and easier to read.
  • Increases Code Reusability: Once a function is written, it can be called multiple times without needing to rewrite the same code.

Syntax for Python Functions

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

Types of Functions in Python

There are two main types of functions in Python:

1. Built-in Functions: These are pre-defined functions provided by Python (e.g., print(), len(), input()).
2. User-defined Functions: Functions that you define yourself based on your needs.

Creating and Calling a Function

In Python, functions are created using the def keyword. After defining the function, it can be called by its name followed by parentheses.

Example of a Simple Function:

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

greet()  # Function call

Output:

Hello, Welcome to Python!

Example: Function to Add Two Numbers:

def add(a: int, b: int) -> int:
    """Returns the sum of two numbers."""
    return a + b

# Function call with arguments
result = add(5, 10)
print(f"Sum of 5 and 10 is {result}")

Output:

Sum of 5 and 10 is 15

Python Function with Return

Functions can return values using the return keyword. This allows you to send back the result of the function to the caller.

Example:

def square(num):
    return num * num

print(square(4))  # Function call

Output:

16

Types of Function Arguments

Python supports different types of arguments that can be passed to functions:

1. Default Arguments: Arguments that assume a default value if not provided in the function call.

Example:

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("John")  # Uses default greeting
greet("Alice", "Good Morning")  # Custom greeting

Output:

Hello, John!
Good Morning, Alice!

2. Keyword Arguments: Arguments where you explicitly define the name of the parameter.

Example:

def student_info(name, age):
    print(f"Name: {name}, Age: {age}")

student_info(age=20, name="John")  # Using keyword arguments

Output:

Name: John, Age: 20

3. Positional Arguments: Arguments are assigned based on their position in the function call.

Example:

def introduce(name, age):
    print(f"Hi, I am {name}, and I am {age} years old.")

introduce("Alice", 25)  # Correct order
introduce(25, "Alice")  # Incorrect order

Output:

Hi, I am Alice, and I am 25 years old.
Hi, I am 25, and I am Alice years old.

4. Arbitrary Arguments (*args and **kwargs):

  • *args: Used to pass a variable number of non-keyword arguments.
  • **kwargs: Used to pass a variable number of keyword arguments.

Example with *args:

def print_args(*args):
    for arg in args:
        print(arg)

print_args("Hello", "Welcome", "to", "Python")

Output:

Hello
Welcome
to
Python

Docstrings

Docstrings provide a description of the function’s purpose and are considered good practice. They are written within triple quotes right after the function definition.

Example:

def even_odd(num):
    """Checks if a number is even or odd."""
    if num % 2 == 0:
        print("Even")
    else:
        print("Odd")

# Accessing docstring
print(even_odd.__doc__)

Output:

Checks if a number is even or odd.

Recursive Functions

A recursive function is one that calls itself. It is useful for problems that can be broken down into smaller instances of the same problem.

Example: Factorial Calculation:

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

print(factorial(5))  # Output: 120

Output:

120

Passing by Reference and Value

In Python, when you pass an object to a function, you are passing a reference to the object, not a copy. So, changes made to the object inside the function will affect the original object.

Example (Passing a List by Reference):

def modify_list(lst):
    lst[0] = 100

lst = [1, 2, 3]
modify_list(lst)
print(lst)  # List is modified

Output:

[100, 2, 3]
End of lesson.