Writing your own function in Python

Understanding Functions in Python

Functions are reusable blocks of code that perform a specific task. They help in organising code, avoiding repetition, and making programs more modular and easier to manage. In Python, functions are defined using the def keyword, followed by the function name and parentheses ().

What Are Functions?

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusability.

Parameters and Arguments

When defining a function, you can specify parameters that act as placeholders for the values you pass to the function. These values are called arguments when you pass them to the function.

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

greet("John")

Output:

Hello, John!

Explanation: In this example, name is a parameter of the function greet. When we call greet("John"), "John" is the argument passed to the function.

Default Values for Arguments

Python allows you to specify default values for parameters. If the function is called without an argument for that parameter, the default value is used.

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

greet()        # Output: Hello, Guest!
greet("John") # Output: Hello, John!

Output:

Hello, Guest!
Hello, Alice!

Explanation: In this example, if greet is called without an argument, it will use the default value "Guest".

Keyword Arguments and Order of Parameters

Functions can also accept arguments as key-value pairs, known as keyword arguments. This allows you to specify the value for a specific parameter without following the order defined in the function signature.

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

describe_pet(pet_name="Whiskers", animal_type="cat")
describe_pet("Buddy") # Uses the default value for animal_type

Output:

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

Explanation: In the first function call, we use keyword arguments to specify pet_name and animal_type. In the second call, only pet_name is provided, so animal_type defaults to "dog".

Using *args and **kwargs

Python provides a way to handle an arbitrary number of arguments using *args and **kwargs.

  • *args is used to pass a variable number of non-keyword arguments to a function.
  • **kwargs allows you to pass a variable number of keyword arguments.
def make_pizza(size, *toppings):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza(16, "pepperoni", "mushrooms", "green peppers")

def build_profile(first, last, **user_info):
    profile = {}
    profile["first_name"] = first
    profile["last_name"] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile("john", "doe", location="vellore", field="civil engineering")
print(user_profile)

Output:

Making a 16-inch pizza with the following toppings:
- pepperoni
- mushrooms
- green peppers
{'first_name': 'john', 'last_name': 'doe', 'location': 'vellore', 'field': 'civil engineering'}

Explanation: The make_pizza function uses *toppings to accept any number of additional arguments, and the build_profile function uses **user_info to accept any number of keyword arguments.

Importance of Order in Parameters

When calling a function, the order of parameters matters, especially when mixing positional and keyword arguments. Positional arguments must be listed before keyword arguments.

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

describe_pet("dog", pet_name="Rover") # Correct
# describe_pet(pet_name="Rover", "dog") # Incorrect - will raise a SyntaxError

Output:

I have a dog named Rover.

Explanation: Positional arguments (like "dog") must be placed before keyword arguments (like pet_name="Rover").

Command Line Arguments

Python scripts can accept command-line arguments, which are values provided to the script when it is executed. These can be accessed using the sys.argv list from the sys module.

import sys

def main():
    if len(sys.argv) != 3:
        print("Usage: script.py <arg1> <arg2>")
    else:
        arg1 = sys.argv[1]
        arg2 = sys.argv[2]
        print(f"Argument 1: {arg1}")
        print(f"Argument 2: {arg2}")

if __name__ == "__main__":
    main()

Output:

Usage: script.py <arg1> <arg2>
đŸ’¡

Note on Dunder Methods

The __name__ and __main__ are known as dunder methods (double underscore methods) in Python. They are used to control the execution of code when a file is run directly. We will study these methods in more detail in the next topic.