Functions in Python

What is a Function?

A function is a reusable block of code designed to perform a specific task. Functions help make programs modular, organized, and easier to maintain.

Defining a Function

def function_name(parameters):
    """Docstring explaining the function."""
    # Function body
    return value

Examples

def greet():
    print("Hello, World!")

greet()
# Output: Hello, World!
  
def add(a, b):
    return a + b

result = add(3, 5)
print(result)
# Output: 8
  
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))
# Output: 120
  
def is_even(num):
    return num % 2 == 0

print(is_even(4))  # True
print(is_even(7))  # False
  
def greet_person(name="Guest"):
    print(f"Hello, {name}!")

greet_person("Alice")
greet_person()
# Output:
# Hello, Alice!
# Hello, Guest!