Python Functions

A function is a reusable block of code that performs a specific task. It helps organize code, reduce repetition, and improve readability.

Defining a Function

Syntax:

def function_name(parameters):
   # code block
   return value  # optional
  • def: Keyword to define a function
  • function_name: Name of the function
  • parameters: (Optional) Values passed into the function
  • return: (Optional) Output returned from the function

Example 1: Basic Function

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

Output:

Hello, World!

Example 2: Function with Parameters

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

Output:

Hello, Alice

Example 3: Function with Return Value

def add(a, b):
   return a + b
result = add(3, 5)
print(result)

Output:

8

Types of Function Arguments

Python supports several types of function arguments:

1. Positional Arguments

def full_name(first, last):
   print(f"{first} {last}")
full_name("John", "Doe")

2. Default Arguments

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

Output:

Hello, Guest!
Hello, Alice!

3. Keyword Arguments

def student(name, age):
   print(name, age)
student(age=20, name="Tom")

4. Arbitrary Arguments (*args)

Accepts multiple positional arguments as a tuple.

def add_all(*args):
   return sum(args)
print(add_all(1, 2, 3, 4))

Output:

10

5. Arbitrary Keyword Arguments (**kwargs)

Accepts multiple keyword arguments as a dictionary.

def display_info(**kwargs):
   for key, value in kwargs.items():
       print(f"{key}: {value}")
display_info(name="Alice", age=25)

Lambda (Anonymous) Functions

A lambda is a short, one-line function.

square = lambda x: x * x
print(square(4))

Output:

16

Recursion: Function Calling Itself

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

Output:

120

The return Statement

  • Ends the function and optionally returns a value.
  • Without return, the function returns None by default.
def get_number():
   return 10
print(get_number())  # 10

Best Practices

  • Use meaningful function names.
  • Keep functions short and focused.
  • Document with docstrings ("""This function does...""").
  • Avoid side effects (modifying global variables, etc.)

Summary Table

KeywordDescription
defDefines a function
returnReturns a result from a function
*argsMultiple positional arguments
**kwargsMultiple keyword arguments
lambdaAnonymous one-line function

Practice Task

Write a function to check if a number is even:

def is_even(n):
   return n % 2 == 0
print(is_even(4))  # True
print(is_even(5))  # False