Python Functions (Methods)
1. What is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing the
same code again and again, we define it once and reuse it.
2. Why Use Functions?
1. Code Reusability: Write once, use many times (DRY principle - Don't Repeat
Yourself)
2. Modularity: Break complex problems into smaller, manageable pieces
3. Readability: Clear, descriptive names make code self-documenting
4. Maintainability: Fix bugs in one place; changes propagate everywhere
5. Testing: Isolate and test individual components
6. Abstraction: Hide complex logic behind simple interfaces
3. Basic Syntax
def function_name(parameters):
# body of function
return value
Explanation:
def → keyword to define function
function_name → name given by programmer
parameters → inputs to function
return → Output value (optional; returns None if omitted)
4. Parameters vs Arguments
Parameter: Variable defined in function definition.
Argument: Actual value passed to function when calling.
def greet(name): # 'name' is parameter
print("Hello", name)
greet("Ali") # 'Ali' is argument
Output:
Hello Ali
5. Default Arguments
Default arguments allow parameters to have default values.
def greet(name="Student"):
print("Hello", name)
greet()
greet("Ali")
Output:
Hello Student
Hello Ali
6. Types of Functions
1. No parameters, no return
def hello():
print("Hi")
hello()
2. Parameters, no return
def add(a, b):
print(a + b)
add(2, 3)
3. No parameters, return value
def get_value():
return 10
print(get_value())
4. Parameters with return
def multiply(a, b):
return a * b
print(multiply(3, 4))
7. Return Keyword
The return keyword sends a value back to the caller and stops execution of function.
8. Lambda Function
Lambda functions are small, anonymous functions defined without a name using
the lambda keyword. They can have any number of arguments but only one expression.
square = lambda x: x * x
print(square(5))
Output:
25
5.2 Lambda with Multiple Arguments
# Multiply two numbers
multiply = lambda a, b: a * b
print(f"Multiply 4 × 5: {multiply(4, 5)}")
# String concatenation
concat = lambda s1, s2: s1 + " " + s2
print(f"Concat: {concat('Hello', 'World')}")
Output:
Multiply 4 × 5: 20
Concat: Hello World
9. Recursion
Recursion is a technique where a function calls itself to solve a problem by breaking it
down into smaller, similar subproblems.
Key Components:
1. Base Case: Stopping condition that prevents infinite recursion
2. Recursive Case: Where the function calls itself with modified parameters
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5))
Output:
120
Explanation:
Function keeps calling itself until base condition is reached.
How it works:
• factorial(5) = 5 * factorial(4)
• factorial(4) = 4 * factorial(3)
• factorial(3) = 3 * factorial(2)
• factorial(2) = 2 * factorial(1)
• factorial(1) = 1 (base case)
• Then unwinds: 2×1=2, 3×2=6, 4×6=24, 5×24=120
10. Built-in Functions
What Are They?
Functions that come with Python automatically. You can use them immediately without
defining anything.
Most Commonly Used Built-in Functions:
Function Purpose Example
print() Display output print("Hello")
input() Get user input name = input("Name: ")
len() Get length len([1,2,3]) → 3
type() Get data type type(5) → <class 'int'>
int() Convert to integer int("123") → 123
str() Convert to string str(123) → "123"
float() Convert to float float("3.14") → 3.14
list() Convert to list list("abc") → ['a','b','c']
range() Generate sequence range(5) → 0,1,2,3,4
sum() Add all items sum([1,2,3]) → 6
min() Find minimum min([1,2,3]) → 1
Function Purpose Example
max() Find maximum max([1,2,3]) → 3
sorted() Sort items sorted([3,1,2]) → [1,2,3]
abs() Absolute value abs(-5) → 5
round() Round number round(3.14159, 2) → 3.14