Python Function Arguments 🎯

When calling a function, we can pass different types of arguments:
✅ Positional Arguments (order matters)
✅ Keyword Arguments (explicitly specify argument names)
✅ Default Arguments (use default values if not provided)
1️⃣ Positional Arguments
📌 Positional arguments must be passed in the correct order.
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet("Alice", 25)
# Output: Hello, my name is Alice and I am 25 years old.
🚨 Order Matters!
greet(25, "Alice")
# Output: Hello, my name is 25 and I am Alice years old. ❌ Incorrect!
2️⃣ Keyword Arguments
📌 With keyword arguments, order doesn't matter because arguments are explicitly named.
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet(age=25, name="Alice")
# Output: Hello, my name is Alice and I am 25 years old. ✅ Correct!
🔹 Mixing Positional & Keyword Arguments
✅ Positional arguments must come first.
greet("Alice", age=25) # ✅ Correct!
greet(name="Alice", 25) # ❌ SyntaxError: Positional argument follows keyword argument
3️⃣ Default Arguments
📌 Default arguments provide a fallback value if no value is passed.
def greet(name="Guest", age=18):
print(f"Hello, my name is {name} and I am {age} years old.")
greet() # Output: Hello, my name is Guest and I am 18 years old.
greet("Alice") # Output: Hello, my name is Alice and I am 18 years old.
greet("Bob", 30) # Output: Hello, my name is Bob and I am 30 years old.
4️⃣ Combining Positional, Keyword & Default Arguments
def introduce(name, age=18, city="New York"):
print(f"My name is {name}, I am {age} years old, and I live in {city}.")
introduce("Alice") # Uses default values: age=18, city="New York"
# Output: My name is Alice, I am 18 years old, and I live in New York.
introduce("Bob", 25, "Los Angeles") # Overrides all defaults
# Output: My name is Bob, I am 25 years old, and I live in Los Angeles.
introduce("Charlie", city="Chicago") # Overrides only city
# Output: My name is Charlie, I am 18 years old, and I live in Chicago.
5️⃣ When to Use Each?
✅ Use positional arguments when order is clear and required.
✅ Use keyword arguments when you want flexibility.
✅ Use default arguments when some values are optional.
Date: 2025-03-22 00:00:00.000000