Python Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs modular.
💻 Basic Function
def greet(name):
return f"Hello, {name}!"
result = greet("Alice")
print(result) # Hello, Alice!
# Function with multiple parameters
def add(a, b):
return a + b
print(add(5, 3)) # 8📝 Default Parameters
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)
# Keyword arguments
def describe_person(name, age, city="Unknown"):
print(f"{name}, {age}, from {city}")
describe_person("Alice", 30)
describe_person(age=25, name="Bob", city="NYC")⭐ *args and **kwargs
# *args: variable number of positional arguments
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs: variable number of keyword arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="NYC")🎯 Key Takeaways
- def: Define a function
- return: Return value from function
- Parameters: Input values for function
- Default values: Optional parameters
- *args: Variable positional arguments
- **kwargs: Variable keyword arguments
- Lambda: Anonymous one-line functions