Python functions


A Python function is a block of reusable code that performs a specific task.

Functions help break down complex problems into smaller, manageable pieces and promote code reusability.

A function is defined using the def keyword followed by the function name and parentheses ().

Creating a Function

To create a function in Python:

  1. Define the function: Use the def keyword.
  2. Name the function: Choose a descriptive name.
  3. Parameters: Inside the parentheses, specify any parameters the function might take.
  4. Function body: Write the code block that performs the task. This block must be indented.
  5. Return statement: (Optional) Use the return statement to return a value from the function.

Example:

Here we have created function using def, provided followed by name and parameter.

To execute (or call) a function, use the function name followed by parentheses, and pass any required arguments inside the parentheses.

def greet(name):
    """This function greets the person passed as a parameter."""
    print(f"Hello, {name}!")

greet("Alice")

Output:

Hello, Alice!

Keyword and Positional Arguments

Positional Arguments

Example:

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

result = add(3, 5)
print(result)

Output:

8

Keyword Arguments

Keyword arguments are passed to the function by explicitly naming each parameter and specifying a value. This allows you to pass arguments in any order.

Example:

def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet(animal_type="dog", pet_name="Rex")
describe_pet(pet_name="Whiskers", animal_type="cat")

Output:

I have a dog named Rex.
I have a cat named Whiskers.

Default Arguments

Default arguments are used when you want to provide a default value for a parameter. If the caller does not provide a value for that parameter, the default value is used.

Example:

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

greet("Alice")
greet("Bob", "Hi")

Output:

Hello, Alice!
Hi, Bob!

Combining Positional, Keyword, and Default Arguments

You can mix positional, keyword, and default arguments. However, there are rules about the order in which you can combine them: positional arguments must come before keyword arguments, and parameters with default values must come after parameters without default values.

Example:

def book_ticket(name, destination, seat="economy"):
    print(f"{name} has booked a {seat} seat to {destination}.")

book_ticket("Alice", "Paris")
book_ticket("Bob", "New York", seat="business")
book_ticket(destination="London", name="Charlie")

Output:

Alice has booked an economy seat to Paris.
Bob has booked a business seat to New York.
Charlie has booked an economy seat to London.
These examples illustrate how to define and call functions in Python, as well as the use of positional and keyword arguments. Functions are a fundamental part of Python programming, enabling code reuse and modularity.