Defining Functions (def) in Python 3

🟢 Beginner Level | Pythonic Code Reusability

📖 Definition

A Python Function is defined using the def keyword, followed by the function name, parameter list (arg1, arg2=default), and an indented 4-space code block ending optionally with a return statement.

🤔 Purpose

Eliminates repetitive code, establishes modular abstractions, and enables clean API signatures.

🌐 Multilingual Explanations

English

Python functions are first-class objects. Missing explicit return implicitly yields None.

Hindi

Python mein def function_name(param): se function banta hai. Return na likhne par default None return hota hai.

Marathi

Function define karnyansathi def keyword vaparatat.

Hinglish

Clean function signature: def greet(name="User"): return f"Hello, {name}" pattern follow karein.

📝 Syntax & Parameters

def function_name(parameter1, parameter2="default_value"):
    """Optional Docstring explaining function purpose."""
    result = parameter1 + parameter2
    return result

⚡ Execution Flow

  1. Python interpreter binds function name to function object during definition pass.
  2. Function call creates a local frame in LEGB scope hierarchy.
  3. Executes indented statements and returns value or None.

💡 Progressive Examples

Example 1: Function with Default Parameters & Docstring

def calculate_total(price: float, tax_rate: float = 0.05) -> float:
    """Calculates final price inclusive of tax."""
    return price * (1 + tax_rate)

print(f"Total: ${calculate_total(100.0):.2f}")
print(f"Total with Custom Tax: ${calculate_total(100.0, 0.10):.2f}")

🖥️ Expected Output

Total: $105.00
Total with Custom Tax: $110.00

🔍 Line-by-Line Code Breakdown

  • def calculate_total(price, tax_rate=0.05): Defines default keyword parameter tax_rate.
  • return price * (1 + tax_rate): Computes and returns floating point total.

⚠️ Variations & Edge Cases

Using a mutable object (like a `list` or `dict`) as a default parameter value leads to shared state bugs!

❌ Common Beginner Mistakes

Mutable Default Arguments: Writing def append_to(element, target=[]) reuses the same list object across calls!

🛠️ Real-World Practical Usage

Data processing utility pipelines in Flask or Django backends.

🎯 Tiered Practice Exercises

  1. Beginner: Write a Python function `is_even(n)` returning boolean True if a number is even.
  2. Intermediate: Create a function taking a string and returning its reverse.
  3. Advanced: Write a decorator function measuring execution time of another function.