Python Programming Lecture Notes Complete
Python Programming Lecture Notes Complete
COMPREHENSIVE LECTURE
NOTES
TABLE OF CONTENTS
1. UNIT I: Introduction to Python Programming
2. UNIT II: Control Structures
3. UNIT III: Functions and Recursion
4. UNIT IV: Objects and Turtle Graphics
5. UNIT V: Dictionaries, Sets, and File Handling
UNIT I: INTRODUCTION TO
PYTHON PROGRAMMING
Computer Hardware
Definition: Physical devices that make up a computer system.
Key Components:
Hardware Hierarchy:
┌─────────────────────────────┐
│ Motherboard (Central) │
├─────────────────────────────┤
│ CPU │ RAM │ GPU │
└─────────────────────────────┘
—2—
│
Storage (SSD/HDD)
Computer Software
Definition: Programs and instructions that tell hardware what to do.
2. LITERALS
Types of Literals
A. String Literals
Definition: Text data enclosed in quotes.
# Single quotes
name = 'Alice'
print(name) # Output: Alice
# Double quotes
message = "Hello, World!"
print(message) # Output: Hello, World!
—3—
paragraph = """Python is a powerful,
easy-to-learn programming language.
It's used in many domains."""
print(paragraph)
Output:
Alice
Hello, World!
Python is a powerful,
easy-to-learn programming language.
It's used in many domains.
Escape Sequences:
\n Newline "Line1\nLine2"
\t Tab "Name\tAge"
\\ Backslash "C:\\Users"
B. Numeric Literals
Integer Literals:
a = 42 # Decimal
b = 0b1010 # Binary (output: 10)
c = 0o12 # Octal (output: 10)
d = 0xFF # Hexadecimal (output: 255)
—4—
Floating-Point Literals:
pi = 3.14159
price = 19.99
scientific = 1.5e-3 # 0.0015
Boolean Literals:
is_student = True
is_employed = False
print(is_student, is_employed)
# Output: True False
Variables
Definition: Named containers that store data values.
# Variable assignment
age = 20
name = "John"
height = 5.9
is_active = True
—5—
print(f"Name: {name}, Age: {age}, Height: {height}, Active: {is_active}")
# Output: Name: John, Age: 20, Height: 5.9, Active: True
Multiple Assignments:
print(x, y, z) # Output: 5 10 15
print(a, b, c) # Output: 5 10 15
print(p, q, r) # Output: 100 100 100
Identifiers
Definition: Names given to variables, functions, classes, etc.
Rules for Identifiers: 1. Must start with letter (a-z, A-Z) or underscore (_) 2. Can
contain letters, digits (0-9), and underscores 3. Cannot contain spaces or special
characters 4. Case-sensitive (age ≠ Age ≠ AGE) 5. Cannot be Python keywords
Valid Identifiers:
Invalid Identifiers:
—6—
my var = 10 # ❌ Contains space
class = "Grade" # ❌ Python keyword
Python Keywords:
False, True, None, and, or, not, if, elif, else, while, for, break,
continue, def, return, class, import, from, try, except, finally,
with, as, pass, lambda, yield
4. OPERATORS
Types of Operators
A. Arithmetic Operators
+ Addition 7 + 3 10
- Subtraction 7 - 3 4
* Multiplication 7 * 3 21
/ Division 7 / 2 3.5
// Floor Division 7 // 2 3
% Modulus 7 % 3 1
** Exponentiation 2 ** 3 8
a = 15
b = 4
—7—
print(f"Multiplication: {a * b}") # Output: 60
print(f"Division: {a / b}") # Output: 3.75
print(f"Floor Division: {a // b}") # Output: 3
print(f"Modulus: {a % b}") # Output: 3
print(f"Exponentiation: {a ** 2}") # Output: 225
Output:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 225
B. Comparison Operators
== Equal to 5 == 5 True
x = 10
y = 5
—8—
print(x >= y) # Output: True
print(x <= y) # Output: False
C. Logical Operators
and Returns True if both conditions are True a > 5 and b < 10
a = 15
b = 8
D. Assignment Operators
= x = 5 Assignment
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
//= x //= 3 x = x // 3
%= x %= 3 x = x % 3
**= x **= 3 x = x ** 3
—9—
x = 10
print(f"Initial: {x}") # Output: 10
x += 5
print(f"After += 5: {x}") # Output: 15
x *= 2
print(f"After *= 2: {x}") # Output: 30
x //= 4
print(f"After //= 4: {x}") # Output: 7
E. Membership Operators
Expressions
Definition: Combinations of values, variables, and operators that evaluate to a result.
# Arithmetic expression
result = 2 + 3 * 4 # = 2 + 12 = 14
print(result) # Output: 14
# String expression
— 10 —
greeting = "Hello" + " " + "World"
print(greeting) # Output: Hello World
# Boolean expression
is_valid = (age >= 18) and (age <= 65)
print(is_valid)
# Example of precedence
result = 2 + 3 * 4 ** 2 # = 2 + 3 * 16 = 2 + 48 = 50
print(result) # Output: 50
Data Types
Definition: Classification of data that determines what operations can be performed.
age = 25
count = -10
binary = 0b1010 # 10 in decimal
Float (float):
pi = 3.14159
temperature = -5.5
scientific = 2.5e-3 # 0.0025
Complex (complex):
— 11 —
z = 3 + 4j # 3 is real part, 4j is imaginary part
print(z) # Output: (3+4j)
print(type(z)) # Output: <class 'complex'>
print([Link]) # Output: 3.0
print([Link]) # Output: 4.0
name = "Alice"
message = 'Hello'
multi_line = """Line 1
Line 2
Line 3"""
String Operations:
str1 = "Hello"
str2 = "World"
# Concatenation
result = str1 + " " + str2
print(result) # Output: Hello World
# Repetition
repeated = "Ha" * 3
print(repeated) # Output: HaHaHa
# Indexing
char = str1[0]
print(char) # Output: H
# Slicing
substr = str1[1:4]
print(substr) # Output: ell
— 12 —
C. Boolean Data Type
is_true = True
is_false = False
# Boolean operations
result1 = True and False # Output: False
result2 = True or False # Output: True
result3 = not True # Output: False
Truth Table:
A B A and B A or B not A
T T T T F
T F F T F
F T F T T
F F F F T
D. Type Conversion
# String to Integer
num_str = "42"
num = int(num_str)
print(num, type(num)) # Output: 42 <class 'int'>
# Integer to String
num = 42
num_str = str(num)
print(num_str, type(num_str)) # Output: 42 <class 'str'>
# String to Float
price_str = "19.99"
price = float(price_str)
print(price, type(price)) # Output: 19.99 <class 'float'>
— 13 —
# Integer to Float
age = 25
age_float = float(age)
print(age_float, type(age_float)) # Output: 25.0 <class 'float'>
6. INPUT/OUTPUT
print("Hello, World!")
Multiple Arguments:
name = "Alice"
age = 20
print("Name:", name, "Age:", age)
# Output: Name: Alice Age: 20
# Custom separator
print("A", "B", "C", sep="-") # Output: A-B-C
# Custom end
print("Hello", end=" ") # Doesn't add newline
print("World")
# Output: Hello World
Formatting Output:
— 14 —
name = "Bob"
age = 30
height = 5.8
# With formatting
pi = 3.14159
print(f"Pi = {pi:.2f}") # Output: Pi = 3.14
name = "Charlie"
age = 25
print("Name: {}, Age: {}".format(name, age))
# Output: Name: Charlie, Age: 25
Method 3: Concatenation:
name = "Diana"
age = 28
print("Name: " + name + ", Age: " + str(age))
# Output: Name: Diana, Age: 28
Example Session:
— 15 —
# Input returns string, need to convert
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")
# Example session:
# Enter your age: 20
# Next year you'll be 21
Multiple Inputs:
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
result = num1 / num2
else:
result = "Invalid operation"
— 16 —
print(f"Result: {result}")
Sample Run:
import math
print(f"Area = {area:.2f}")
print(f"Perimeter = {perimeter:.2f}")
Sample Run:
print(f"{celsius}°C = {fahrenheit}°F")
— 17 —
Sample Run:
5 Mark Questions:
Q1: Explain different types of literals in Python with examples.
Answer:
Literals are fixed values written in code. Types include:
1. String Literals: "Hello", 'World' (enclosed in quotes)
2. Numeric Literals: 42 (int), 3.14 (float)
3. Boolean Literals: True, False
4. Special Literal: None
Example:
— 18 —
name = "Alice" # String literal
age = 25 # Integer literal
height = 5.8 # Float literal
is_student = True # Boolean literal
Q2: What is the difference between int and float data types?
Answer:
| Feature | int | float |
|---------|-----|-------|
| Format | Whole numbers | Decimal numbers |
| Size | Limited | Larger range |
| Example | 42, -10 | 3.14, -5.5 |
| Memory | Less | More |
Code:
a = 42 # int
b = 42.0 # float
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
Answer:
Precedence determines order of evaluation:
1. ** (exponentiation)
2. *, /, //, % (multiplication, division)
3. +, - (addition, subtraction)
4. <, >, <=, >=, ==, != (comparison)
5. and, or, not (logical)
Example:
2 + 3 * 4 = 2 + 12 = 14 (not 20)
2 ** 3 * 2 = 8 * 2 = 16
Q4: What are identifiers? List the rules for naming identifiers.
Answer:
Identifiers are names for variables, functions, etc.
— 19 —
Rules:
1. Must start with letter or underscore
2. Can contain letters, digits, underscores
3. Case-sensitive
4. Cannot be keywords
5. No spaces or special characters
Answer:
| Feature | input() | print() |
|---------|---------|---------|
| Purpose | Read from user | Display output |
| Returns | String | None |
| Example | name = input("Enter:") | print("Hello") |
| Output | User sees prompt | Displays text |
Code:
name = input("Enter name: ") # Gets input
print(f"Hello, {name}") # Shows output
10 Mark Questions:
Q1: Explain data types in Python with their operations and type conversion.
Answer:
Data Types in Python:
— 20 —
3. BOOLEAN DATA TYPE
- True or False
- Result of comparison/logical operations
TYPE CONVERSION:
int(3.14) → 3
float(42) → 42.0
str(100) → "100"
int("50") → 50
Sample Run:
Enter a number: 5
Square = 25
Answer:
Program:
a = 20
b = 10
c = 5
# Arithmetic operations
print(f"Addition: {a + b}") # 30
print(f"Subtraction: {a - b}") # 10
print(f"Multiplication: {b * c}") # 50
print(f"Division: {a / b}") # 2.0
print(f"Floor Division: {a // b}") # 2
print(f"Modulus: {a % b}") # 0
print(f"Exponentiation: {c ** 2}") # 25
# Precedence demonstration
result = a + b * c # = 20 + 50 = 70
— 21 —
print(f"20 + 10 * 5 = {result}")
result = (a + b) * c # = 30 * 5 = 150
print(f"(20 + 10) * 5 = {result}")
Output:
Addition: 30
Subtraction: 10
Multiplication: 50
Division: 2.0
Floor Division: 2
Modulus: 0
Exponentiation: 25
20 + 10 * 5 = 70
(20 + 10) * 5 = 150
Q3: Write a program that takes user input and demonstrates output
formatting.
Answer:
Program:
# Get user input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
salary = float(input("Enter your salary: "))
# f-string formatting
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Salary: ${salary:.2f}")
# format() method
print("\nUsing format():")
print("Name: {}, Age: {}, Salary: ${:.2f}".format(name, age, salary))
# Concatenation
print("\nUsing concatenation:")
print("Name: " + name + ", Age: " + str(age))
— 22 —
# Multiple formatting
print(f"\n{name} is {age} years old with salary of ${salary:.2f}")
Sample Run:
Enter your name: Alice
Enter your age: 25
Enter your salary: 50000
Name: Alice
Age: 25
Salary: $50000.00
Using format():
Name: Alice, Age: 25, Salary: $50000.00
Using concatenation:
Name: Alice, Age: 25
Answer:
Program:
# Simple Interest = (Principal * Rate * Time) / 100
— 23 —
# Calculation
simple_interest = (principal * rate * time) / 100
total_amount = principal + simple_interest
Sample Run:
=== SIMPLE INTEREST CALCULATOR ===
Answer:
COMPARISON OPERATORS: Compare two values, return boolean
- == (equal), != (not equal)
- > (greater), < (less)
- >= (greater or equal), <= (less or equal)
— 24 —
Program:
a = 15
b = 8
# Comparison operators
print("=== COMPARISON OPERATORS ===")
print(f"{a} == {b}: {a == b}") # False
print(f"{a} != {b}: {a != b}") # True
print(f"{a} > {b}: {a > b}") # True
print(f"{a} < {b}: {a < b}") # False
print(f"{a} >= {b}: {a >= b}") # True
# Logical operators
print("\n=== LOGICAL OPERATORS ===")
print(f"({a} > 10) and ({b} > 5): {(a > 10) and (b > 5)}") # True
print(f"({a} > 10) and ({b} > 10): {(a > 10) and (b > 10)}") # False
print(f"({a} > 20) or ({b} > 5): {(a > 20) or (b > 5)}") # True
print(f"not ({a} > 20): {not (a > 20)}") # True
Output:
=== COMPARISON OPERATORS ===
15 == 8: False
15 != 8: True
15 > 8: True
15 < 8: False
15 >= 8: True
— 25 —
UNIT II: CONTROL STRUCTURES
Definition: Control structures direct the flow of program execution based on conditions.
┌────────────────────┐
│ CONTROL STRUCTURES │
├────────────────────┤
│ Selection │ (if, elif, else)
│ Iteration │ (while, for)
│ Jumping │ (break, continue)
└────────────────────┘
Why Control Structures? - Make decisions based on conditions - Repeat code blocks
efficiently - Change program flow dynamically
2. BOOLEAN EXPRESSIONS
# Comparison-based
x = 10
print(x > 5) # Output: True
print(x == 10) # Output: True
print(x < 5) # Output: False
— 26 —
Complex Boolean Expressions
age = 25
income = 50000
# Using and
is_eligible = (age >= 18) and (income > 30000)
print(is_eligible) # Output: True
# Using or
is_member = (age < 18) or (income > 100000)
print(is_member) # Output: False
# Using not
is_invalid = not (age >= 18)
print(is_invalid) # Output: False
AND Operation:
T and T = T T and F = F
F and T = F F and F = F
OR Operation:
T or T = T T or F = T
F or T = T F or F = F
NOT Operation:
not T = F not F = T
Truthiness in Python:
# False values
print(bool(0)) # False
print(bool("")) # False (empty string)
print(bool([])) # False (empty list)
print(bool(None)) # False
# True values
print(bool(1)) # True
— 27 —
print(bool("hello")) # True
print(bool([1, 2])) # True
3. SELECTION CONTROL
The if Statement
Syntax:
if condition:
# Code executes if condition is True
statement1
statement2
Flowchart:
┌─────────┐
│ Condition?
└────┬────┘
│
╔══╧══╗
║ ║
T F
║ ║
V V
Execute Skip
Block (go to next)
│ │
└──┬──┘
V
Example 1: Simple if
age = 18
— 28 —
print("You are an adult")
score = 85
# Output:
# Grade: A
# Excellent performance!
# Keep it up!
if condition:
# Code if True
statement1
else:
# Code if False
statement2
Flowchart:
┌─────────┐
│ Condition?
└────┬────┘
│
╔══╧══╗
║ ║
T F
║ ║
V V
— 29 —
Block1 Block2
│ │
└──┬──┘
V
Example:
age = 15
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
statement4
Flowchart:
┌──────────┐
│ Condition1?
└────┬─────┘
│
╔══╧══╗
T F
║ ║
│ ┌──────────┐
│ │ Condition2?
— 30 —
│ └────┬─────┘
│ │
│ ╔══╧══╗
│ T F
V ║ ║
Block1│ ┌──────────┐
│ │ Condition3?
│ └────┬─────┘
│ │
│ ╔══╧══╗
│ T F
V ║ ║
Block2│ Block3
V
Block4
score = 75
4. INDENTATION IN PYTHON
— 31 —
Key Rule: Python uses indentation to define code blocks, not braces.
# Correct indentation
if age >= 18:
print("Adult") # Indented (part of if block)
print("Can vote") # Indented (part of if block)
print("End") # Not indented (outside if block)
# Output:
# Adult
# Can vote
# End
Wrong Indentation:
if condition1: # No indent
statement1 # 4 spaces
if condition2: # 4 spaces
statement2 # 8 spaces
statement3 # 8 spaces
statement4 # 4 spaces
statement5 # No indent
5. MULTI-WAY SELECTION
— 32 —
Using if-elif-else
def get_day_name(day_num):
if day_num == 1:
return "Monday"
elif day_num == 2:
return "Tuesday"
elif day_num == 3:
return "Wednesday"
elif day_num == 4:
return "Thursday"
elif day_num == 5:
return "Friday"
elif day_num == 6:
return "Saturday"
elif day_num == 7:
return "Sunday"
else:
return "Invalid day"
Nested if Statements
age = 25
income = 50000
— 33 —
Example: Nested Multi-way Selection
marks = 85
# Output: Grade: A
6. ITERATIVE CONTROL
while condition:
# Code executes as long as condition is True
statement1
statement2
Flowchart:
┌──────────┐
│ Condition?
└────┬─────┘
│
╔══╧══╗
— 34 —
║ ║
T F
║ ║
V │
Execute │
Block │
│ │
└─┐ │
│ │
(Go back to condition)
│
V
Continue
count = 1
# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5
num = 1
total = 0
— 35 —
Infinite Loops
Definition: A loop that never ends because the condition is always True.
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
# Output:
# Enter 'quit' to exit: hello
# You entered: hello
# Enter 'quit' to exit: world
# You entered: world
# Enter 'quit' to exit: quit
— 36 —
count = 1
while count < 10:
if some_condition():
break
count += 1
Boolean Flag
Definition: A Boolean variable used to control loop execution.
if not found:
print(f"{target} not found")
valid_input = False
— 37 —
# Output:
# Enter age (0-120): 150
# Invalid age, try again
# Enter age (0-120): 25
# Valid age: 25
String Manipulation
String Creation:
s1 = "Hello"
s2 = 'World'
s3 = """Multi-line
String"""
String Operations:
Length len("Hello") 5
text = "Python"
# Length
print(len(text)) # Output: 6
— 38 —
# Indexing
print(text[0]) # Output: P
print(text[-1]) # Output: n (last character)
# Slicing
print(text[1:4]) # Output: yth
print(text[:3]) # Output: Pyt
print(text[3:]) # Output: hon
# String methods
print([Link]()) # Output: PYTHON
print([Link]()) # Output: python
print([Link]("Python", "Java")) # Output: Java
List Manipulation
Definition: Ordered collection of items (can be mixed types).
List Creation:
# Empty list
list1 = []
# Mixed types
list3 = [1, "Hello", 3.14, True]
# Nested list
list4 = [[1, 2], [3, 4], [5, 6]]
List Operations:
# Length
print(len(numbers)) # Output: 5
# Indexing
print(numbers[0]) # Output: 10
— 39 —
print(numbers[-1]) # Output: 50
# Slicing
print(numbers[1:3]) # Output: [20, 30]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[2:]) # Output: [30, 40, 50]
# Remove value
[Link](25)
print(numbers) # Output: [10, 20, 30, 40, 50, 60]
# Membership check
print(30 in numbers) # Output: True
print(100 in numbers) # Output: False
List Iteration:
# Output:
# apple
# banana
# orange
— 40 —
Dictionary Manipulation
Definition: Collection of key-value pairs (unordered).
Dictionary Creation:
# Empty dictionary
dict1 = {}
# Mixed types
info = {
"id": 1,
"name": "Bob",
"scores": [85, 90, 88]
}
Dictionary Operations:
student = {
"name": "Alice",
"age": 20,
"city": "New York"
}
# Accessing values
print(student["name"]) # Output: Alice
print([Link]("age")) # Output: 20
# Modifying value
student["age"] = 21
— 41 —
del student["city"]
# All keys
print([Link]()) # Output: dict_keys(['name', 'age', 'grade'])
# All values
print([Link]()) # Output: dict_values(['Alice', 21, 'A'])
# All items
print([Link]())
# Output: dict_items([('name', 'Alice'), ('age', 21), ('grade', 'A')])
Dictionary Iteration:
# Output:
# name: Charlie
# age: 25
# city: Boston
— 42 —
# 1. Import statements
import math
from datetime import datetime
# 2. Function definitions
def calculate_area(radius):
"""Calculate circle area"""
return [Link] * radius ** 2
# Process
area = calculate_area(r)
# Output
print(f"Area: {area:.2f}")
# Main program
num = int(input("Enter number: "))
if num < 0:
print("Error: negative number")
elif num == 0 or num == 1:
print(f"Factorial of {num} is 1")
else:
print(f"Factorial of {num} is {factorial(num)}")
# Sample run:
— 43 —
# Enter number: 5
# Factorial of 5 is 120
Syntax:
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # start to stop-1, increment by step
Examples:
# Single argument
for i in range(5):
print(i) # Output: 0 1 2 3 4
# Two arguments
for i in range(2, 6):
print(i) # Output: 2 3 4 5
nums = list(range(5))
print(nums) # Output: [0, 1, 2, 3, 4]
— 44 —
nums = list(range(10, 20, 2))
print(nums) # Output: [10, 12, 14, 16, 18]
# Without index
for fruit in fruits:
print(fruit)
# Output:
# 0: apple
# 1: banana
# 2: orange
break Statement
Definition: Exits the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4
— 45 —
numbers = [3, 7, 2, 9, 5, 1, 8]
target = 9
# Output:
# Checking 3
# Checking 7
# Checking 2
# Checking 9
# Found 9!
continue Statement
Definition: Skips current iteration and continues with next.
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
# Output: 1 3 5 7 9
for i in range(5):
num = int(input(f"Enter number {i+1}: "))
if num < 0:
print("Negative number, skipping")
continue
print(f"Processed: {num}")
# Sample output:
# Enter number 1: 10
— 46 —
# Processed: 10
# Enter number 2: -5
# Negative number, skipping
# Enter number 3: 20
# Processed: 20
Syntax:
Examples:
— 47 —
12. COMPLETE PROGRAM EXAMPLES
import random
# Sample run:
# Guess the number between 1 and 100!
# Enter your guess: 50
# Too high, try again!
# Enter your guess: 25
# Too low, try again!
# Enter your guess: 35
# Correct! You won in 3 attempts!
— 48 —
"Bob": 92,
"Charlie": 78,
"Diana": 88,
"Eve": 65
}
# Output:
# === GRADE REPORT ===
#
# Alice | Score: 85 | Grade: B
# Bob | Score: 92 | Grade: A
# Charlie | Score: 78 | Grade: C
# Diana | Score: 88 | Grade: B
# Eve | Score: 65 | Grade: D
while True:
print("\n=== SHOPPING LIST ===")
print("1. Add item")
print("2. Remove item")
— 49 —
print("3. View list")
print("4. Exit")
if choice == '1':
item = input("Enter item to add: ")
shopping_list.append(item)
print(f"Added: {item}")
else:
print("Invalid choice")
— 50 —
13. KEY CONCEPTS SUMMARY
5 Mark Questions:
Q1: Explain the difference between while and for loops.
Answer:
while loop: Repeats while condition is True
- Unknown number of iterations
- Used for indefinite loops
- Must manually update condition variable
Example:
count = 0
while count < 5:
print(count)
count += 1
— 51 —
- Used for definite loops
- Automatically iterates through sequence
Example:
for i in range(5):
print(i)
Both output: 0 1 2 3 4
Answer:
A Boolean flag is a Boolean variable (True/False) used to control
program flow.
Example:
found = False
numbers = [3, 5, 7, 9]
if found:
print("Number found")
else:
print("Number not found")
Answer:
1. STRING: Sequence of characters
name = "Alice"
name[0] = 'A'
name[1:4] = 'lic'
— 52 —
numbers[0] = 10
Answer:
Indentation is the whitespace at the beginning of a line that
defines code blocks in Python.
Example:
if age >= 18: # No indent
print("Adult") # 4 spaces (part of if block)
print("Can vote") # 4 spaces (part of if block)
print("Done") # No indent (outside if block)
Answer:
break: Exits loop immediately
Example:
for i in range(10):
if i == 5:
break
print(i)
Output: 0 1 2 3 4
— 53 —
print(i)
Output: 0 1 3 4
10 Mark Questions:
Q1: Write a program to find maximum of three numbers using if-elif-else.
Answer:
Program:
# Get three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
Sample Run:
Enter first number: 10
Enter second number: 25
Enter third number: 15
Maximum: 25
Answer:
Program:
# Get number from user
num = int(input("Enter number for multiplication table: "))
— 54 —
while multiplier <= 10:
product = num * multiplier
print(f"{num} x {multiplier} = {product}")
multiplier += 1
Sample Run:
Enter number for multiplication table: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Q3: Write a program to work with lists - add, remove, and display items.
Answer:
Program:
# Initialize empty list
items = []
# Menu-driven program
while True:
print("\n=== LIST OPERATIONS ===")
print("1. Add item")
print("2. Remove item")
print("3. Display list")
print("4. Exit")
if choice == '1':
item = input("Enter item to add: ")
[Link](item)
print(f"Added: {item}")
— 55 —
if items:
print("Items:", items)
item = input("Enter item to remove: ")
if item in items:
[Link](item)
print(f"Removed: {item}")
else:
print("Item not found")
else:
print("List is empty")
else:
print("Invalid choice")
Sample Output:
=== LIST OPERATIONS ===
1. Add item
2. Remove item
3. Display list
4. Exit
Enter choice: 1
Enter item to add: apple
Added: apple
(continues with user input)
— 56 —
Answer:
Program:
# Initialize dictionary
students = {}
while True:
print("\n=== STUDENT MANAGEMENT ===")
print("1. Add student")
print("2. View student")
print("3. Display all students")
print("4. Exit")
if choice == '1':
roll_no = input("Enter roll number: ")
name = input("Enter name: ")
marks = float(input("Enter marks: "))
if roll_no in students:
info = students[roll_no]
print(f"Name: {info['name']}, Marks: {info['marks']}")
else:
print("Student not found")
— 57 —
break
else:
print("Invalid choice")
Sample Output:
=== STUDENT MANAGEMENT ===
1. Add student
2. View student
3. Display all students
4. Exit
Enter choice: 1
Enter roll number: 101
Enter name: Alice
Enter marks: 85
Student added successfully
(continues with more interactions)
Answer:
Program:
# Get three sides from user
print("Enter three sides of triangle:")
a = float(input("Side 1: "))
b = float(input("Side 2: "))
c = float(input("Side 3: "))
Sample Runs:
— 58 —
Run 1:
Enter three sides of triangle:
Side 1: 5
Side 2: 5
Side 3: 5
Equilateral triangle
Run 2:
Enter three sides of triangle:
Side 1: 5
Side 2: 5
Side 3: 7
Isosceles triangle
Run 3:
Enter three sides of triangle:
Side 1: 3
Side 2: 4
Side 3: 5
Scalene triangle
Run 4:
Enter three sides of triangle:
Side 1: 1
Side 2: 2
Side 3: 10
Not a valid triangle
— 59 —
UNIT III: FUNCTIONS AND
RECURSION
1. PROGRAM ROUTINES
Program Organization:
┌──────────────────────────────────┐
│ MAIN PROGRAM FLOW │
├──────────────────────────────────┤
│ Routine 1 → Routine 2 → Routine 3
│ │ │ │
│ Task1 Task2 Task3
└──────────────────────────────────┘
2. DEFINING FUNCTIONS
Syntax:
def function_name(parameters):
"""Docstring - description of function"""
# Function body
statement1
statement2
return result
— 60 —
def greet():
"""Greet the user"""
print("Hello, Welcome!")
# Call function
result = add(5, 3)
print(f"Sum: {result}") # Output: Sum: 8
# Using function
result = area_of_rectangle(10, 5)
print(f"Area: {result}") # Output: Area: 50
Function Components:
— 61 —
Component Purpose Example
Syntax:
result = function_name(arguments)
def square(num):
"""Return square of number"""
return num ** 2
result = square(5)
print(result) # Output: 25
def get_min_max(numbers):
"""Return minimum and maximum"""
return min(numbers), max(numbers)
nums = [3, 7, 2, 9, 5]
minimum, maximum = get_min_max(nums)
print(f"Min: {minimum}, Max: {maximum}")
# Output: Min: 2, Max: 9
— 62 —
def calculate_discount(price, discount_percent):
"""Calculate discounted price"""
discount = price * (discount_percent / 100)
return price - discount
original_price = 100
final_price = calculate_discount(original_price, 20)
print(f"Final Price: ${final_price}") # Output: Final Price: $80.0
def display_message(message):
"""Display a message"""
print(f"Message: {message}")
display_message("Hello, Python!")
# Output: Message: Hello, Python!
count = 0
def increment():
"""Increment count"""
global count
count += 1
print(f"Count: {count}")
— 63 —
def print_stars(num):
"""Print stars in a line"""
for i in range(num):
print("*", end="")
print() # Newline
print_stars(5)
print_stars(10)
# Output:
# *****
# **********
5. PARAMETER PASSING
def modify_value(x):
"""Modify integer parameter"""
x = x + 10
print(f"Inside function: {x}")
num = 5
modify_value(num)
print(f"Outside function: {num}")
# Output:
# Inside function: 15
# Outside function: 5
— 64 —
Pass by Reference (Mutable Types)
def modify_list(lst):
"""Modify list parameter"""
[Link](100)
print(f"Inside function: {lst}")
numbers = [1, 2, 3]
modify_list(numbers)
print(f"Outside function: {numbers}")
# Output:
# Inside function: [1, 2, 3, 100]
# Outside function: [1, 2, 3, 100]
Immutable Mutable
Changes inside function don’t affect original Changes inside function affect original
— 65 —
# Keyword arguments (order doesn't matter)
person_info(city="Boston", age=30, name="Bob")
# Mixed
person_info("Charlie", age=35, city="Chicago")
# Output:
# Name: Alice, Age: 25, City: New York
# Name: Bob, Age: 30, City: Boston
# Name: Charlie, Age: 35, City: Chicago
Syntax:
def function_name(parameter=default_value):
pass
— 66 —
def greet(name="Guest"):
"""Greet with name"""
print(f"Hello, {name}!")
create_profile("Bob")
create_profile("Charlie", 25)
create_profile("Diana", 30, "Boston")
# Output:
# Name: Bob, Age: 18, City: Unknown
# Name: Charlie, Age: 25, City: Unknown
# Name: Diana, Age: 30, City: Boston
print(f"Name: {name}")
print(f"Items: {items}, Count: {count}, Active: {active}")
process_data("Alice")
process_data("Bob", [1, 2, 3], 3)
# Output:
# Name: Alice
# Items: [], Count: 0, Active: True
— 67 —
# Name: Bob
# Items: [1, 2, 3], Count: 3, Active: True
8. VARIABLE SCOPE
Types of Scope:
Local Scope
def function1():
x = 10 # Local variable
print(x)
function1() # Output: 10
# print(x) # Error: x not defined outside function
Global Scope
y = 20 # Global variable
def function2():
print(y) # Can access global
function2() # Output: 20
print(y) # Output: 20
count = 0 # Global
def increment():
global count # Declare global
count += 1
— 68 —
increment()
print(count) # Output: 1
increment()
print(count) # Output: 2
Scope Hierarchy:
┌────────────────────────────────┐
│ GLOBAL SCOPE │
│ (Accessible everywhere) │
│ │
│ ┌────────────────────────┐ │
│ │ LOCAL SCOPE (func1) │ │
│ │ (Only in function) │ │
│ └────────────────────────┘ │
│ │
│ ┌────────────────────────┐ │
│ │ LOCAL SCOPE (func2) │ │
│ │ (Only in function) │ │
│ └────────────────────────┘ │
└────────────────────────────────┘
Complete Example:
def outer_function():
outer_var = "I'm in outer"
def inner_function():
inner_var = "I'm in inner"
print(inner_var) # Local - OK
print(outer_var) # Outer - OK
print(global_var) # Global - OK
inner_function()
outer_function()
— 69 —
# Output:
# I'm in inner
# I'm in outer
# I'm global
Key Components: 1. Base Case: Stops recursion 2. Recursive Case: Function calls
itself with simpler input
Flowchart:
┌─────────────────────┐
│ recursive_function()
├─────────────────────┤
│ Base Case? │
│ │ │ │
│ YES NO │
│ │ │ │
│ Return Recursive
│ Value Call
│ │ │
│ └─────┬────┘
│ V
│ Return
└─────────────────────┘
Example 1: Factorial
Without Recursion (Iterative):
def factorial_iterative(n):
"""Calculate factorial using loop"""
result = 1
for i in range(2, n + 1):
result *= i
— 70 —
return result
With Recursion:
def factorial(n):
"""Calculate factorial using recursion"""
# Base case
if n <= 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
Execution Trace:
factorial(5)
= 5 * factorial(4)
= 5 * (4 * factorial(3))
= 5 * (4 * (3 * factorial(2)))
= 5 * (4 * (3 * (2 * factorial(1))))
= 5 * (4 * (3 * (2 * 1)))
= 5 * (4 * (3 * 2))
= 5 * (4 * 6)
= 5 * 24
= 120
def fibonacci(n):
"""Return nth Fibonacci number"""
# Base cases
if n <= 0:
return 0
elif n == 1:
return 1
— 71 —
# Recursive case
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Output: 0 1 1 2 3 5 8 13 21 34
def sum_numbers(n):
"""Sum of numbers from 1 to n"""
# Base case
if n == 0:
return 0
# Recursive case
else:
return n + sum_numbers(n - 1)
result = sum_numbers(5)
print(f"Sum from 1 to 5: {result}") # Output: Sum from 1 to 5: 15
Recursion vs Iteration:
— 72 —
Aspect Recursion Iteration
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit"""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius"""
return (fahrenheit - 32) * 5/9
# Usage
temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C = {temp_f}°F")
temp_f = 77
temp_c = fahrenheit_to_celsius(temp_f)
print(f"{temp_f}°F = {temp_c}°C")
# Output:
# 25°C = 77.0°F
# 77°F = 25.0°C
— 73 —
Example 2: Prime Number Checker
def is_prime(num):
"""Check if number is prime"""
if num < 2:
return False
# Test
numbers = [2, 4, 7, 10, 13, 15, 17]
for num in numbers:
if is_prime(num):
print(f"{num} is prime")
else:
print(f"{num} is not prime")
# Output:
# 2 is prime
# 4 is not prime
# 7 is prime
# 10 is not prime
# 13 is prime
# 15 is not prime
# 17 is prime
# Test
— 74 —
print(gcd(48, 18)) # Output: 6
print(gcd(100, 50)) # Output: 50
def is_palindrome(text):
"""Check if string is palindrome"""
text = [Link]().replace(" ", "")
return text == text[::-1]
# Test
words = ["racecar", "hello", "madam", "python"]
for word in words:
if is_palindrome(word):
print(f"'{word}' is a palindrome")
else:
print(f"'{word}' is not a palindrome")
# Output:
# 'racecar' is a palindrome
# 'hello' is not a palindrome
# 'madam' is a palindrome
# 'python' is not a palindrome
— 75 —
Concept Purpose Example
5 Mark Questions:
Q1: What is a function? Explain its benefits.
Answer:
A function is a named block of code that performs a specific task.
Syntax:
def function_name(parameters):
"""Docstring"""
statement1
statement2
return result
Benefits:
1. Code reusability - write once, use many times
2. Modular design - break problem into smaller pieces
3. Easy to debug - isolate issues
4. Better organization - cleaner code structure
5. Reduced duplication - less repeated code
Example:
def add(a, b):
"""Add two numbers"""
return a + b
— 76 —
Answer:
Parameters: Variables in function definition
Arguments: Values passed when calling function
Example:
def greet(name, age): # name, age are PARAMETERS
print(f"{name} is {age}")
Answer:
Scope is the region where a variable is accessible.
Types:
1. Local scope: Inside function only
2. Global scope: Accessible everywhere
Example:
global_x = 10 # Global
def func():
local_y = 5 # Local
print(global_x) # Can access global
print(local_y) # Can access local
func()
print(global_x) # Can access global
# print(local_y) # Error: local_y not accessible
Answer:
Recursion: A function that calls itself.
— 77 —
Factorial Example:
def factorial(n):
if n <= 1: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
Answer:
Default arguments are values assigned to parameters if not provided.
Syntax:
def function_name(parameter=default_value):
pass
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
Another Example:
def describe(name, age=18, city="Unknown"):
print(f"{name}, {age}, {city}")
10 Mark Questions:
Q1: Write a program with functions to calculate simple interest and compound
interest.
— 78 —
Answer:
Program:
def simple_interest(principal, rate, time):
"""Calculate simple interest"""
si = (principal * rate * time) / 100
return si
print(f"Principal: ${principal}")
print(f"Rate: {rate}%")
print(f"Time: {time} years")
print(f"Simple Interest: ${si:.2f}")
print(f"Compound Interest: ${ci:.2f}")
print(f"Difference: ${(ci - si):.2f}")
# Main program
principal = float(input("Enter principal: "))
rate = float(input("Enter rate (%): "))
time = float(input("Enter time (years): "))
Sample Output:
Enter principal: 10000
Enter rate (%): 5
Enter time (years): 3
Principal: $10000.00
Rate: 5.0%
Time: 3.0 years
Simple Interest: $1500.00
— 79 —
Compound Interest: $1576.25
Difference: $76.25
Answer:
Program:
def fibonacci(n):
"""Return nth Fibonacci number recursively"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def print_fibonacci_series(count):
"""Print first 'count' Fibonacci numbers"""
print(f"First {count} Fibonacci numbers:")
for i in range(count):
print(fibonacci(i), end=" ")
print()
def fibonacci_sum(n):
"""Calculate sum of first n Fibonacci numbers"""
total = 0
for i in range(n):
total += fibonacci(i)
return total
# Main program
num = int(input("Enter number of terms: "))
print_fibonacci_series(num)
print(f"\nSum of first {num} terms: {fibonacci_sum(num)}")
Sample Output:
Enter number of terms: 10
First 10 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34
Sum of first 10 terms: 88
— 80 —
Q3: Write a program with multiple functions and demonstrate scope.
Answer:
Program:
global_counter = 0 # Global variable
def increment_global():
"""Modify global variable"""
global global_counter
global_counter += 1
def process_data():
"""Function demonstrating local scope"""
local_var = 100
print(f"Local variable: {local_var}")
print(f"Global counter: {global_counter}")
def main():
"""Main function"""
print("=== SCOPE DEMONSTRATION ===\n")
increment_global()
increment_global()
print("After incrementing:", global_counter)
process_data()
if __name__ == "__main__":
main()
— 81 —
Sample Output:
=== SCOPE DEMONSTRATION ===
Answer:
Program:
def is_palindrome(text):
"""Check if string is palindrome"""
cleaned = [Link]().replace(" ", "")
return cleaned == cleaned[::-1]
def count_vowels(text):
"""Count vowels in string"""
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
def reverse_string(text):
"""Reverse a string"""
return text[::-1]
def display_string_info(text):
"""Display all string information"""
print(f"Original: {text}")
print(f"Length: {len(text)}")
print(f"Reversed: {reverse_string(text)}")
print(f"Vowels: {count_vowels(text)}")
print(f"Is Palindrome: {is_palindrome(text)}")
— 82 —
# Main program
text = input("Enter a string: ")
display_string_info(text)
Sample Output:
Enter a string: racecar
Original: racecar
Length: 7
Reversed: racecar
Vowels: 3
Is Palindrome: True
Answer:
Program:
def create_student_record(name, roll_no, stream="Science", grade="A", marks=0):
"""Create student record with default arguments"""
print(f"Name: {name}")
print(f"Roll No: {roll_no}")
print(f"Stream: {stream}")
print(f"Grade: {grade}")
print(f"Marks: {marks}\n")
# Main program
print("=== POSITIONAL ARGUMENTS ===")
create_student_record("Alice", 101)
create_student_record("Bob", 102, "Commerce")
— 83 —
print_record(roll_no=105, name="Eve", stream="Science", marks=88)
Sample Output:
=== POSITIONAL ARGUMENTS ===
Name: Alice
Roll No: 101
Stream: Science
Grade: A
Marks: 0
Name: Bob
Roll No: 102
Stream: Commerce
Grade: A
Marks: 0
Record of Eve
Roll: 105, Stream: Science, Marks: 88%
— 84 —
UNIT IV: OBJECTS AND THEIR
USE
1. SOFTWARE OBJECTS
Definition: Instances of classes that combine data (attributes) and behavior (methods).
Why Objects? - Model real-world entities - Organize code logically - Encapsulate related
data and functions
Object Structure:
┌──────────────────────┐
│ OBJECT │
├──────────────────────┤
│ ATTRIBUTES (Data) │ Properties
│ - name │
│ - age │
│ - color │
├──────────────────────┤
│ METHODS (Behavior) │ Functions
│ - move() │
│ - speak() │
│ - eat() │
└──────────────────────┘
# Define a class
class Dog:
def __init__(self, name, age):
[Link] = name # Attribute
[Link] = age # Attribute
— 85 —
def get_age(self): # Method
return [Link]
# Access attributes
print(f"Dog 1: {[Link]}, Age: {[Link]}")
print(f"Dog 2: {[Link]}, Age: {[Link]}")
# Call methods
[Link]()
[Link]()
# Output:
# Dog 1: Buddy, Age: 3
# Dog 2: Max, Age: 5
# Buddy says Woof!
# Max says Woof!
2. TURTLE GRAPHICS
— 86 —
Command Purpose Example
import turtle
# Create a screen
screen = [Link]()
[Link]("Draw a Square")
# Create a turtle
pen = [Link]()
[Link](1)
# Draw a square
for i in range(4):
[Link](100)
[Link](90)
— 87 —
[Link]()
import turtle
[Link](0)
# Draw circle
[Link]("blue")
[Link](100)
# Draw dot
[Link]()
[Link](0, -100)
[Link]()
[Link](20, "red")
[Link]()
[Link]()
import turtle
— 88 —
[Link]()
[Link](150)
[Link]()
[Link]()
[Link]()
import turtle
[Link](0)
[Link]("blue")
for i in range(36):
[Link](i * 5)
[Link](10)
[Link]()
[Link]()
3. TURTLE ATTRIBUTES
import turtle
t = [Link]()
# Position
[Link]() # X coordinate
[Link]() # Y coordinate
[Link]() # (x, y) position
# Heading (direction)
[Link]() # Current heading (0-360 degrees)
— 89 —
[Link](90) # Set heading
# Speed
[Link](0) # Speed 0-10 (0 = fastest)
# Pen attributes
[Link]() # Get pen width
[Link]() # Get pen color
# Visibility
[Link]() # Show turtle
[Link]() # Hide turtle
[Link]() # Check if visible
# Drawing state
[Link]() # Check if pen up/down
# More operations
[Link](x, y) # Set position
[Link](angle) # Set heading direction
import turtle
screen = [Link]()
t = [Link]()
# Set attributes
[Link](2)
[Link](3)
[Link]("red")
[Link]("arrow")
— 90 —
# Rotate
[Link](45)
[Link](50)
[Link]()
4. MODULAR DESIGN
┌───────────────────────────┐
│ MAIN PROGRAM │
├───────────────────────────┤
│ Module 1 │ Module 2 │
│ ───────── │ ───────── │
│ - Func A │ - Func C │
│ - Func B │ - Func D │
└───────────────────────────┘
— 91 —
if b != 0:
return a / b
else:
return "Cannot divide by zero"
def get_numbers():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
return a, b
if choice == '5':
print("Goodbye!")
break
if choice == '1':
print(f"Result: {add(a, b)}")
elif choice == '2':
print(f"Result: {subtract(a, b)}")
elif choice == '3':
print(f"Result: {multiply(a, b)}")
elif choice == '4':
print(f"Result: {divide(a, b)}")
else:
print("Invalid choice")
— 92 —
if __name__ == "__main__":
main()
5. MODULES
Built-in Modules:
import math
import random
import datetime
from turtle import Turtle
Module Usage:
— 93 —
Module Purpose Examples
6. TOP-DOWN DESIGN
Process:
┌─────────────────────────────────┐
│ MAIN PROBLEM │
└────────────────────┬────────────┘
│
┌────────────┼────────────┐
│ │ │
┌───V───┐ ┌───V───┐ ┌───V────┐
│Module1│ │Module2│ │Module3 │
└───┬───┘ └───┬───┘ └────┬───┘
│ │ │
┌───V───┐ ┌───V────┐ ┌────V────┐
│Task 1 │ │Task 2 │ │Task 3 │
│Task 2 │ │Task 3 │ │Task 4 │
└───────┘ └────────┘ └─────────┘
— 94 —
print("3. Reports")
print("4. Exit")
choice = input("Choose: ")
if choice == '1':
account_management()
elif choice == '2':
transactions()
elif choice == '3':
reports()
elif choice == '4':
break
def create_account():
# Code for creating account
pass
def delete_account():
# Code for deleting account
pass
# Module 2: Transactions
def transactions():
print("\n=== TRANSACTIONS ===")
print("1. Deposit")
print("2. Withdraw")
def deposit():
# Code for deposit
pass
def withdraw():
# Code for withdrawal
pass
# Module 3: Reports
— 95 —
def reports():
print("\n=== REPORTS ===")
print("1. Account Statement")
if __name__ == "__main__":
bank_system()
7. PYTHON MODULES
File: math_operations.py
PI = 3.14159
File: [Link]
print(f"Sum: {result1}")
print(f"Product: {result2}")
print(f"Pi: {PI}")
# Output:
# Sum: 8
— 96 —
# Product: 24
# Pi: 3.14159
5 Mark Questions:
Q1: What are objects and classes? Explain with example.
Answer:
Class: Blueprint/template for creating objects
Object: Instance of a class
Example:
class Student:
def __init__(self, name, roll_no):
[Link] = name # Attribute
self.roll_no = roll_no # Attribute
— 97 —
def display(self): # Method
print(f"{[Link]} - {self.roll_no}")
# Create objects
s1 = Student("Alice", 101)
s2 = Student("Bob", 102)
Output:
Alice - 101
Bob - 102
Answer:
Modular design: Breaking program into independent modules.
Benefits:
1. Easy to understand - each module has specific purpose
2. Easy to test - test each module separately
3. Easy to maintain - fix bugs in isolated module
4. Code reuse - use modules in different programs
5. Team work - different people can work on different modules
Example structure:
Module 1: Input/Output
Module 2: Processing
Module 3: Reporting
Answer:
Turtle graphics: Module for creating drawings using virtual turtle.
Basic Commands:
1. [Link](100) - Move forward
2. [Link](50) - Move backward
3. [Link](90) - Turn right 90°
4. [Link](45) - Turn left 45°
— 98 —
5. [Link]() - Lift pen (no draw)
6. [Link]() - Put pen down (draw)
7. [Link]("red") - Change color
8. [Link](50) - Draw circle
9. [Link](10, "blue") - Draw dot
10. [Link]() - Hide turtle
Answer:
Modules: Files containing Python code for reuse.
Types:
1. Built-in modules - Part of Python
2. Custom modules - Created by programmer
Built-in Examples:
import math
import random
import datetime
from turtle import Turtle
Common functions:
[Link](16) → 4.0
[Link](1, 10) → random number
[Link]() → current date/time
Answer:
Top-down design: Breaking complex problem into smaller subproblems.
Process:
1. Define main problem
2. Break into modules
3. Break modules into functions
4. Implement smallest pieces first
Example:
Main: Bank System
├─ Account Management
— 99 —
│ ├─ Create Account
│ └─ Delete Account
├─ Transactions
│ ├─ Deposit
│ └─ Withdraw
└─ Reports
└─ Statement
10 Mark Questions:
Q1: Create a class for a Bank Account with deposit, withdraw, and balance
methods.
Answer:
Program:
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
[Link] = initial_balance
def get_balance(self):
— 100 —
"""Get current balance"""
return [Link]
def display_info(self):
"""Display account info"""
print(f"Account Holder: {self.account_holder}")
print(f"Balance: ${[Link]:.2f}")
# Main program
account = BankAccount("Alice", 1000)
account.display_info()
[Link](500)
print(f"Balance: ${account.get_balance():.2f}")
[Link](200)
print(f"Balance: ${account.get_balance():.2f}")
account.display_info()
Sample Output:
Account Holder: Alice
Balance: $1000.00
Deposited: $500.00
Balance: $1500.00
Withdrew: $200.00
Balance: $1300.00
Account Holder: Alice
Balance: $1300.00
Answer:
Program:
import turtle
— 101 —
[Link](size)
[Link](90)
t.end_fill()
def draw_house():
"""Draw complete house"""
screen = [Link]()
[Link]("House")
t = [Link]()
[Link](1)
# Draw door
[Link]()
[Link](-25, -50)
[Link]()
[Link]("brown")
draw_square(t, 50, "brown")
— 102 —
# Draw windows
[Link]()
[Link](-60, 30)
[Link]()
[Link]("cyan")
draw_square(t, 30, "cyan")
[Link]()
[Link](30, 30)
[Link]()
draw_square(t, 30, "cyan")
[Link]()
[Link]()
# Run
draw_house()
Dictionary Creation:
— 103 —
"grade": "A",
"city": "New York"
}
Dictionary Operations:
# Accessing values
print(student["name"]) # Output: Alice
print([Link]("age")) # Output: 20
print([Link]("gpa", 3.8)) # Default if not found
# Adding/Updating
student["grade"] = "A" # Add new key
student["age"] = 21 # Update existing
# Deleting
del student["city"]
[Link]("grade")
# Checking existence
if "name" in student:
print("Name exists")
# Dictionary length
print(len(student)) # 2
— 104 —
# Clearing dictionary
[Link]() # Empty dictionary
Dictionary Methods:
Dictionary Iteration:
# Iterate keys
for key in person:
print(key)
# Output:
# name
# age
# city
— 105 —
#
# name: Charlie
# age: 30
# city: Boston
#
# Charlie
# 30
# Boston
Nested Dictionaries:
school = {
"students": {
"001": {"name": "Alice", "marks": 85},
"002": {"name": "Bob", "marks": 90}
},
"teachers": {
"T001": {"name": "Mr. Smith", "subject": "Math"}
}
}
Set Creation:
— 106 —
# Method 3: Empty set
set3 = set() # Not {} which is dict
Set Operations:
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Length
print(len(set1)) # Output: 5
# Membership test
print(3 in set1) # Output: True
print(10 in set1) # Output: False
# Adding elements
[Link](6)
[Link]([7, 8])
# Removing elements
[Link](1) # No error if not found
[Link](2) # Error if not found
[Link]() # Remove random element
# Set operations
union = set1 | set2 # Combine
intersection = set1 & set2 # Common
difference = set1 - set2 # In set1 but not set2
symmetric_diff = set1 ^ set2 # In either but not both
# Methods
[Link](set2)
[Link](set2)
[Link](set2)
Set Relationships:
— 107 —
set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}
set_c = {6, 7, 8}
Set vs List:
Set List
Unordered Ordered
{1, 2, 3} [1, 2, 3]
File Modes:
— 108 —
Opening Files:
Example:
Methods to Read:
— 109 —
for line in lines:
print([Link]())
Example Program:
read_file("[Link]")
Writing Methods:
— 110 —
# Method 2: writelines() - Multiple strings
with open("[Link]", "w") as file:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
[Link](lines)
Example Program:
# Data
students = [
{"name": "Alice", "roll": 101, "marks": 85},
{"name": "Bob", "roll": 102, "marks": 90},
{"name": "Charlie", "roll": 103, "marks": 78}
]
save_students(students, "[Link]")
print("Students saved to file")
6. EXCEPTION HANDLING
Exception Types:
— 111 —
Exception Cause Example
try-except Structure:
try:
# Code that might cause error
risky_operation()
except SpecificError:
# Handle specific error
print("Specific error occurred")
except Exception as e:
# Handle general error
print(f"Error: {e}")
else:
# Executes if no error
print("Success!")
finally:
# Always executes
print("Cleanup")
try:
with open("[Link]", "r") as file:
content = [Link]()
except FileNotFoundError:
print("Error: File not found")
except IOError:
print("Error: Cannot read file")
else:
— 112 —
print("File read successfully")
finally:
print("Operation completed")
while True:
try:
age = int(input("Enter age: "))
if 0 < age < 150:
print(f"Valid age: {age}")
break
else:
print("Age must be between 0 and 150")
except ValueError:
print("Error: Please enter a valid number")
try:
numbers = [1, 2, 3]
index = int(input("Enter index: "))
value = numbers[index]
result = 100 / value
print(f"Result: {result}")
except ValueError:
print("Error: Enter a valid number")
except IndexError:
print("Error: Index out of range")
except ZeroDivisionError:
print("Error: Cannot divide by zero")
except Exception as e:
print(f"Unexpected error: {e}")
— 113 —
7. COMPLETE FILE HANDLING PROGRAM
import os
class StudentRecords:
def __init__(self, filename="[Link]"):
[Link] = filename
def read_all(self):
"""Read all students"""
try:
with open([Link], "r") as file:
print("\n=== STUDENT RECORDS ===")
for line in file:
name, roll, marks = [Link]().split(",")
print(f"Name: {name}, Roll: {roll}, Marks: {marks}")
except FileNotFoundError:
print("Error: File not found")
— 114 —
if not found:
print(f"Student {name} not found")
except FileNotFoundError:
print("Error: File not found")
# Main program
records = StudentRecords()
# Add students
records.add_student("Alice", 101, 85)
records.add_student("Bob", 102, 90)
records.add_student("Charlie", 103, 78)
# Read all
records.read_all()
# Search
records.search_student("Alice")
# Output:
# Student Alice added successfully
# Student Bob added successfully
# Student Charlie added successfully
#
# === STUDENT RECORDS ===
# Name: Alice, Roll: 101, Marks: 85
# Name: Bob, Roll: 102, Marks: 90
# Name: Charlie, Roll: 103, Marks: 78
# Found: Name: Alice, Roll: 101, Marks: 85
— 115 —
Concept Description Example
5 Mark Questions:
Q1: Explain dictionaries and their operations.
Answer:
Dictionary: Collection of key-value pairs (mutable, unordered)
Operations:
1. Create: student = {"name": "Alice", "age": 20}
2. Access: student["name"] → "Alice"
3. Add: student["grade"] = "A"
4. Update: student["age"] = 21
5. Delete: del student["grade"]
6. Check: "name" in student → True
Methods:
[Link]() - Get all keys
[Link]() - Get all values
[Link]() - Get key-value pairs
[Link]("key", default) - Safe access
Answer:
Set: Unordered collection of unique, immutable items
Creation:
set1 = {1, 2, 3, 4}
— 116 —
set2 = set([1, 2, 2, 3]) → {1, 2, 3} (duplicates removed)
Operations:
[Link](5) - Add element
[Link](2) - Remove element
union = set1 | set2 - Combine
intersection = set1 & set2 - Common
difference = set1 - set2 - Only in set1
Answer:
File modes:
- "r" (Read) - Default, read existing file
- "w" (Write) - Create/overwrite file
- "a" (Append) - Add to end of file
- "x" (Create) - Create new file
Opening files:
Method 1: Basic
file = open("[Link]", "r")
content = [Link]()
[Link]()
Answer:
Exception: Runtime errors that can be handled.
Common exceptions:
- ValueError: int("abc")
- TypeError: "text" + 5
- ZeroDivisionError: 10 / 0
- FileNotFoundError: open("[Link]")
— 117 —
Handling:
try:
risky_code()
except ValueError:
print("Value error")
except Exception as e:
print(f"Error: {e}")
else:
print("Success")
finally:
print("Cleanup")
Answer:
Dictionary:
- Key-value pairs
- Mutable
- Access by key
- {key: value}
- Duplicate keys not allowed
Set:
- Single values
- Mutable
- No indexing
- {value1, value2}
- No duplicates
- Unique items only
10 Mark Questions:
Q1: Write program for dictionary operations and iteration.
Answer:
Program:
— 118 —
# Create dictionary
employee = {
"id": 101,
"name": "Alice",
"department": "IT",
"salary": 50000,
"years": 5
}
# Display
print("Original dictionary:")
for key, value in [Link]():
print(f"{key}: {value}")
# Add
employee["location"] = "Boston"
print(f"\nAfter adding location: {employee['location']}")
# Update
employee["salary"] = 55000
print(f"Updated salary: {employee['salary']}")
# Delete
del employee["years"]
print(f"Removed 'years' key")
# Get
name = [Link]("name", "Not found")
print(f"Employee name: {name}")
# Check
if "department" in employee:
print(f"Department: {employee['department']}")
Sample Output:
— 119 —
=== DICTIONARY OPERATIONS ===
Original dictionary:
id: 101
name: Alice
department: IT
salary: 50000
years: 5
Answer:
Program:
# Create sets
numbers1 = {1, 2, 3, 4, 5}
numbers2 = {3, 4, 5, 6, 7}
print(f"Set 1: {numbers1}")
print(f"Set 2: {numbers2}")
# Union
union = numbers1 | numbers2
print(f"\nUnion: {union}")
# Intersection
intersection = numbers1 & numbers2
print(f"Intersection: {intersection}")
# Difference
— 120 —
diff1 = numbers1 - numbers2
diff2 = numbers2 - numbers1
print(f"In Set 1 but not Set 2: {diff1}")
print(f"In Set 2 but not Set 1: {diff2}")
# Symmetric difference
sym_diff = numbers1 ^ numbers2
print(f"Symmetric difference: {sym_diff}")
# Membership
print(f"\n3 in Set 1: {3 in numbers1}")
print(f"10 in Set 1: {10 in numbers1}")
Sample Output:
=== SET OPERATIONS ===
Set 1: {1, 2, 3, 4, 5}
Set 2: {3, 4, 5, 6, 7}
Union: {1, 2, 3, 4, 5, 6, 7}
Intersection: {3, 4, 5}
In Set 1 but not Set 2: {1, 2}
In Set 2 but not Set 1: {6, 7}
Symmetric difference: {1, 2, 6, 7}
3 in Set 1: True
10 in Set 1: False
Q3: Write complete file handling program for reading and writing.
Answer:
Program:
— 121 —
def write_data(filename):
"""Write data to file"""
try:
with open(filename, "w") as file:
[Link]("Product\tPrice\tQuantity\n")
[Link]("Laptop\t$999\t5\n")
[Link]("Mouse\t$25\t20\n")
[Link]("Keyboard\t$75\t15\n")
print(f"Data written to {filename}")
except IOError:
print(f"Error: Cannot write to {filename}")
def read_data(filename):
"""Read data from file"""
try:
with open(filename, "r") as file:
print(f"\nContents of {filename}:\n")
for line_num, line in enumerate(file, 1):
print(f"{line_num}: {[Link]()}")
except FileNotFoundError:
print(f"Error: {filename} not found")
def count_lines(filename):
"""Count lines in file"""
try:
with open(filename, "r") as file:
lines = [Link]()
print(f"Total lines: {len(lines)}")
except FileNotFoundError:
print(f"Error: {filename} not found")
def append_data(filename):
"""Append data to file"""
try:
with open(filename, "a") as file:
[Link]("Monitor\t$300\t8\n")
print(f"Data appended to {filename}")
except IOError:
print(f"Error: Cannot write to {filename}")
# Main program
filename = "[Link]"
— 122 —
# Write
write_data(filename)
# Read
read_data(filename)
# Count
count_lines(filename)
# Append
append_data(filename)
# Read again
read_data(filename)
Sample Output:
Data written to [Link]
Contents of [Link]:
Contents of [Link]:
Answer:
Program:
def safe_file_operation():
— 123 —
"""Demonstrate exception handling in file operations"""
# Run
— 124 —
try:
safe_file_operation()
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("Program ended")
Q5: Write program to read CSV file and process data with exception handling.
Answer:
Program:
import os
def process_csv_file(filename):
"""Read CSV file and calculate statistics"""
try:
with open(filename, "r") as file:
print(f"Reading file: {filename}\n")
# Read header
header = [Link]().strip()
print(f"Header: {header}\n")
marks_list = []
# Read data
for line in file:
try:
parts = [Link]().split(",")
if len(parts) < 3:
print(f"Warning: Invalid format - {[Link]()}")
continue
name = parts[0]
roll = parts[1]
marks = float(parts[2])
— 125 —
except ValueError:
print(f"Error: Invalid marks value in line - {[Link]()}")
# Calculate statistics
if marks_list:
avg = sum(marks_list) / len(marks_list)
max_marks = max(marks_list)
min_marks = min(marks_list)
except FileNotFoundError:
print(f"Error: File '{filename}' not found")
except IOError:
print(f"Error: Cannot read file '{filename}'")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("\nFile processing completed")
# Main program
# First, create sample CSV file
def create_sample_file():
try:
with open("[Link]", "w") as file:
[Link]("Name,Roll,Marks\n")
[Link]("Alice,101,85\n")
[Link]("Bob,102,90\n")
[Link]("Charlie,103,78\n")
[Link]("Diana,104,92\n")
print("Sample file created: [Link]\n")
except IOError:
print("Error: Cannot create file")
— 126 —
Sample Output:
Sample file created: [Link]
Header: Name,Roll,Marks
UNIT I: Fundamentals - Variables, Operators, Data Types, I/O UNIT II: Control Flow - if/
elif/else, while/for loops, Lists, Dictionaries UNIT III: Functions - Definition, Parameters,
Recursion, Scope UNIT IV: Objects - Classes, Turtle Graphics, Modules, Design UNIT V:
Advanced - Dictionaries, Sets, Files, Exception Handling
— 127 —
END OF COMPREHENSIVE
LECTURE NOTES
— 128 —