Web Development
HTML Course
CSS Course
JavaScript Course
PHP Course
Python Course
SQL Course
SEO Course

Functions in Python

Functions are reusable blocks of code that allow you to structure programs efficiently. They can accept parameters, return values, and can be customized in countless ways.

Defining functions

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

Parameters and return values

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

result = add(3, 5)
print(result)   # Prints: 8

Default arguments and *args - **kwargs

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

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

def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))   # Prints: 6

def details(**info):
    print(info)

details(name="John", age=30)

Docstrings and comments

def multiply(a, b):
    """Returns the product of two numbers."""
    return a * b

# Simple comment
# This function multiplies two values

Lambda functions

square = lambda x: x * x
print(square(4))   # Prints: 16

Useful built-in functions

print(len("Python"))     # 6
print(sum([1, 2, 3]))    # 6
print(range(5))          # range(0, 5)

Recursion

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

print(factorial(5))   # Prints: 120
Note:
  • Functions can be documented with """docstring""" for clarity.
  • Arguments *args and **kwargs provide flexibility in calls.
  • Lambda functions are useful for short expressions but do not replace classic functions.
  • Recursion should be used carefully โ€” it can lead to stack overflow errors.

๐Ÿง  Quiz - Functions in Python

Top