10
Day 10: Functions
Chapter 10 • Intermediate
50 min
Functions are reusable blocks of code that perform a specific task. They help organize code, make it more readable, and avoid repetition.
Function Definition:
- Use def keyword to define a function
- Function name should be descriptive
- Parameters are optional
- Return statement is optional
Function Types:
- Built-in functions (print, len, etc.)
- User-defined functions
- Lambda functions (anonymous functions)
- Recursive functions
Function Parameters:
- Positional arguments
- Keyword arguments
- Default parameters
- Variable-length arguments (*args, **kwargs)
Hands-on Examples
Function Basics
# Simple function
def greet():
print("Hello, World!")
greet()
# Function with parameters
def greet_person(name, age):
print(f"Hello {name}, you are {age} years old")
greet_person("Priya", 25)
# Function with return value
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(f"Sum: {result}")
# Function with default parameters
def greet_with_default(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet_with_default("Marcus")
greet_with_default("Sofia", "Hi")
# Function with multiple return values
def get_name_and_age():
return "Aisha", 30
name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}")
# Lambda function
square = lambda x: x ** 2
print(f"Square of 5: {square(5)}")Functions help organize code and make it reusable. Lambda functions are useful for simple operations.