Functions

Functions in Python: Imagine you are a chef in a busy restaurant. You have a specific recipe for "Tomato Soup." Instead of writing out every single step (wash…

Concept Explanation

Imagine you are a chef in a busy restaurant. You have a specific recipe for "Tomato Soup." Instead of writing out every single step (wash tomatoes, chop them, boil water...) every time someone orders the soup, you just say, "Cook Tomato Soup."

In Python, a Function is that recipe. It is a block of code which only runs when it is "called." You can pass data (parameters) into a function, and it can return data as a result. Functions are the most powerful tool for keeping your code DRY (Don't Repeat Yourself).


Syntax or Core Structure

Defining and Calling

Use the def keyword to define a function, followed by its name and parentheses.

# Definition
def greet_user():
    print("Hello! Welcome to the Python Course.")

# Calling (Execution)
greet_user()

Arguments and Return Values

  • Parameters: The variable names inside the function definition.
  • Arguments: The actual values you send to the function when calling it.
  • Return: The keyword that sends a result back to the caller.
def add_numbers(a, b):
    result = a + b
    return result

total = add_numbers(5, 10)
print(f"The sum is: {total}")

Code Example #1 (Basic)

Default values and keyword arguments.

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

# Using default value
describe_pet("Buddy")

# Overriding default value
describe_pet("Whiskers", "Cat")

# Using keyword arguments (order doesn't matter!)
describe_pet(animal_type="Hamster", name="Cheeks")

Code Example #2 (Intermediate)

Handling a flexible number of arguments with *args and **kwargs.

# *args allows any number of positional arguments (tuple)
def make_pizza(size, *toppings):
    print(f"Making a {size}-inch pizza with:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza(12, "Mushrooms", "Green Peppers", "Extra Cheese")

# **kwargs allows any number of keyword arguments (dictionary)
def build_profile(first, last, **user_info):
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

user = build_profile('Harsh', 'Developer', location='India', field='AI')
print(user)

Real World Example

Imagine you are building a currency converter for a travel app.

# 💱 Currency Converter Service
def convert_to_usd(amount, rate):
    """Converts a local currency amount to USD."""
    if amount <= 0:
        return 0
    return round(amount * rate, 2)

# Usage across different parts of the app
flight_price_in_inr = 55000
conversion_rate = 0.012

total_usd = convert_to_usd(flight_price_in_inr, conversion_rate)

print(f"The ticket costs approximately ${total_usd} USD.")

Common Mistakes

  1. Confusing Print vs. Return: This is a major hurdle. print() shows a value to the human, but return gives the value back to the code. If a function doesn't have a return, it technically returns None.
  2. Variable Shadowing: If you have a global variable named x and a local function parameter named x, the function will use its own internal x. This can lead to confusing bugs if you're not careful.
  3. Mutable Default Arguments: NEVER use a list or dictionary as a default value (e.g., def add(x, list=[])). Because Python only creates that list once when the function is defined, it will "remember" previous calls, leading to weird behavior. Use None instead.

Best Practices

  • Docstrings: Always add a triple-quoted string right at the start of your function explains what it does, what it takes, and what it returns.
  • Small and Focused: A function should do one thing well. If your function is 100 lines long, it's probably doing too much—break it into smaller helper functions.

Practice Exercises

  1. The Area Calculator: Write a function called calculate_rectangle_area(width, height). It should return the area. If the user only provides width, assume it's a square (width = height).
  2. The List Summarizer: Write a function that takes a list of numbers and returns a tuple containing: (Sum of numbers, Average of numbers, Maximum number).
  3. The Formatter: Create a function that takes a first name and last name and returns a neatly formatted "Last Name, First Name" string.