Open Category List

Functions in Python

1 minuteread

Functions are blocks of code that perform a specific task and can be reused throughout your code. They help in making code modular and organized.

Defining a Function:

def function_name(parameters):
    """
    Docstring (optional): Describe what the function does.
    """
    # Function body
    return value  # Optional

Example:

def greet(name):
    """Greets a person with the given name."""
    return f"Hello, {name}!"

# Calling the function
message = greet("Alice")
print(message)  # Output: Hello, Alice!

Parameters and Arguments:

  • Positional Arguments: Passed in order.
  • Keyword Arguments: Passed by name.
  • Default Parameters: Parameters with default values.
  • Arbitrary Arguments:
    • *args: Non-keyword variable-length arguments.
    • **kwargs: Keyword variable-length arguments.

Example with Default and Arbitrary Arguments:

def make_pizza(size, *toppings):
    """Summarize the pizza we are about to make."""
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza(12, 'pepperoni')
make_pizza(16, 'mushrooms', 'green peppers', 'extra cheese')

Related Knowledge Base Posts