Python Functions Lecture
Python Functions Lecture
🔥 EXAM TIP: Always include docstring in exam answers for extra marks!
2. TYPES OF FUNCTIONS
A) Built-in Functions (Definition + Examples)
Definition: Pre-defined functions provided by Python that are ready to use.
Common Examples for Exams:
len("Python") # Returns 6
max(10, 20, 5) # Returns 20
min(10, 20, 5) # Returns 5
abs(-15) # Returns 15
round(3.14159, 2) # Returns 3.14
sum([1,2,3,4]) # Returns 10
B) User-defined Functions (Most Important for Exams)
Definition: Functions created by programmers to solve specific problems.
📝 EXAM ANSWER FORMAT:
def calculate_area(length, width):
"""Calculate area of rectangle"""
area = length * width
return area
# Function call
result = calculate_area(5, 3)
print(result) # Output: 15
🎯 EXAM PATTERN: Questions often ask to differentiate between functions with and without
return statements.
# Output:
# Name: John
# Age: 18
# Grade: A
🎯 EXAM TIP: In mixed arguments, positional arguments MUST come before keyword
arguments.
# Using defaults
print(calculate_interest(1000)) # Output: 50.0
# Overriding some defaults
print(calculate_interest(1000, rate=7.0)) # Output: 70.0
# WRONG - SyntaxError
def func(a=5, b, c=20): # Non-default after default
pass
total = sum(numbers)
average = total / len(numbers)
return average
**How *args works**: - Collects extra positional arguments into a tuple - Can be used with
regular parameters - Must come after regular parameters
# Output:
# Student: Alice, Grade: A
# Additional Information:
# age: 18
# city: Delhi
# hobby: Reading
How kwargs works**: - Collects extra keyword arguments into a dictionary - Parameter
name can be anything (not just ‘kwargs’) - Must come after *args if both are used
# Example calls
complete_function("A")
complete_function("A", "B", 1, 2, 3, name="John", age=25)
print(f"Salary: {salary}")
print(f"Tax: {tax}")
calculate_tax()
Key Points for Exam: - Local variables exist only inside the function - Cannot be accessed
outside the function - Different functions can have variables with same names
def display_info():
"""Access global variables"""
print(f"Company: {company_name}") # Accessing global
print(f"Employees: {total_employees}") # Accessing global
def add_employee():
"""Modify global variable"""
global total_employees # Must use 'global' keyword
total_employees += 1
print(f"Total employees now: {total_employees}")
def deposit(amount):
"""Deposit money - modifies global variable"""
global balance # MUST declare global
balance += amount
print(f"Deposited: ${amount}")
print(f"New balance: ${balance}")
def withdraw(amount):
"""Withdraw money - modifies global variable"""
global balance # MUST declare global
if balance >= amount:
balance -= amount
print(f"Withdrawn: ${amount}")
print(f"Remaining balance: ${balance}")
else:
print("Insufficient funds!")
def check_balance():
"""Check balance - only reads global variable"""
print(f"Current balance: ${balance}") # No 'global' needed for
reading
# Function calls
check_balance() # Current balance: $1000
deposit(500) # Deposited: $500, New balance: $1500
withdraw(200) # Withdrawn: $200, Remaining balance: $1300
check_balance() # Current balance: $1300
def increment():
counter = counter + 1 # ERROR! UnboundLocalError
print(counter)
# CORRECT VERSION:
def increment():
global counter
counter = counter + 1
print(counter)
5. RECURSION ⭐⭐⭐⭐
✍️DEFINITION (Write exactly in exam)
Recursion is a programming technique where a function calls itself to solve a problem by
breaking it down into smaller, similar subproblems.
# Recursive case
return n * factorial(n - 1)
# Test cases
print(f"5! = {factorial(5)}") # Output: 5! = 120
print(f"0! = {factorial(0)}") # Output: 0! = 1
print(f"1! = {factorial(1)}") # Output: 1! = 1
Working backwards:
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120
# Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)
# Output:
# F(0) = 0, F(1) = 1, F(2) = 1, F(3) = 2
# F(4) = 3, F(5) = 5, F(6) = 8, F(7) = 13
# Recursive case
return (n % 10) + sum_of_digits(n // 10)
# Test
print(sum_of_digits(12345)) # Output: 15 (1+2+3+4+5)
print(sum_of_digits(987)) # Output: 24 (9+8+7)
# Recursive case
return base * power(base, exponent - 1)
print(power(2, 5)) # Output: 32 (2^5)
print(power(3, 4)) # Output: 81 (3^4)
add = lambda a, b: a + b
print(add(10, 20)) # Output: 30
# Multiple arguments
calculate = lambda x, y, z: (x + y) * z
print(calculate(2, 3, 4)) # Output: 20
# String operations
full_name = lambda first, last: f"{first} {last}"
print(full_name("John", "Doe")) # Output: John Doe
# Sort by marks
by_marks = sorted(students, key=lambda student: student[1])
print(by_marks) # Output: [('Charlie', 78), ('Alice', 85), ('Bob',
92)]
Example Comparison:
# Lambda function
square_lambda = lambda x: x ** 2
return total_amount
# Recursive case
return gcd(b, a % b)
# Test cases
print(f"GCD of 48 and 18: {gcd(48, 18)}") # Output: 6
print(f"GCD of 100 and 25: {gcd(100, 25)}") # Output: 25
print(f"GCD of 17 and 13: {gcd(17, 13)}") # Output: 1
# Display results
print("All students with averages:")
for student in students_with_avg:
print(f"{student['name']}: {student['average']:.2f}")
2. Global Variable:
global variable_name
3. Lambda Syntax:
4. Recursive Structure:
if base_case:
return base_value
return recursive_call