Functions in Python

1/7/2025

Functions in Python

Functions are reusable blocks of code that perform specific tasks.

Defining Functions

python
def greet(name):
    return f"Hello, {name}!"

print(greet("World"))  # Hello, World!

Default Parameters

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

greet("John")            # Hello, John!
greet("John", "Hi")      # Hi, John!

Keyword Arguments

python
def create_user(name, age, email):
    return {"name": name, "age": age, "email": email}

user = create_user(
    email="[email protected]",
    name="John",
    age=30
)

*args and **kwargs

python
def sum_all(*args):
    return sum(args)

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

sum_all(1, 2, 3, 4)  # 10
print_info(name="John", age=30)

Lambda Functions

python
square = lambda x: x ** 2
add = lambda a, b: a + b

print(square(5))  # 25
print(add(2, 3))  # 5