0% found this document useful (0 votes)
2 views128 pages

Python Programming Lecture Notes Complete

The document provides comprehensive lecture notes on Python programming, covering essential topics such as control structures, functions, recursion, and data types. It includes detailed explanations of computer science fundamentals, Python syntax, operators, and input/output methods. The material is designed for college students to facilitate their understanding of Python programming concepts.

Uploaded by

Kala Surya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views128 pages

Python Programming Lecture Notes Complete

The document provides comprehensive lecture notes on Python programming, covering essential topics such as control structures, functions, recursion, and data types. It includes detailed explanations of computer science fundamentals, Python syntax, operators, and input/output methods. The material is designed for college students to facilitate their understanding of Python programming concepts.

Uploaded by

Kala Surya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

COMPREHENSIVE LECTURE
NOTES

Complete Study Material for College Students

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

1. OVERVIEW AND FUNDAMENTALS

What is Computer Science?


Computer Science is the study of computation, automation, and information. It involves:
- Hardware: Physical components (CPU, RAM, storage) - Software: Programs and
applications - Algorithms: Step-by-step procedures to solve problems - Data
Structures: Ways to organize and store data

Computer Hardware
Definition: Physical devices that make up a computer system.

Key Components:

Component Function Example

CPU Processes instructions Intel i7, AMD Ryzen

RAM Temporary storage 8GB, 16GB DDR4

Storage Permanent storage SSD, HDD

Motherboard Connects all components Main circuit board

GPU Graphics processing NVIDIA GeForce

Hardware Hierarchy:

┌─────────────────────────────┐
│ Motherboard (Central) │
├─────────────────────────────┤
│ CPU │ RAM │ GPU │
└─────────────────────────────┘

—2—

Storage (SSD/HDD)

Computer Software
Definition: Programs and instructions that tell hardware what to do.

Types of Software: 1. System Software: Operating systems (Windows, Linux,


macOS) 2. Application Software: Programs users run (browsers, editors, IDEs) 3.
Utility Software: Tools for maintenance (antivirus, backup)

Python Programming Language


Why Python? - ✅ Easy to learn syntax (English-like) - ✅ Versatile (web, data science, AI,
automation) - ✅ Large community and libraries - ✅ Cross-platform compatible - ✅ Widely
used in industry

Python Version: Python 3.x (current standard)

2. LITERALS

Definition: Fixed values written directly in code that don’t change.

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!

# Triple quotes (multi-line)

—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:

Escape Sequence Meaning Example

\n Newline "Line1\nLine2"

\t Tab "Name\tAge"

\\ Backslash "C:\\Users"

\' Single quote "It\'s"

\" Double quote "He said \"Hi\""

print("Hello\tWorld") # Output: Hello World


print("Path: C:\\Users\\Documents") # Output: Path: C:\Users\Documents

B. Numeric Literals
Integer Literals:

a = 42 # Decimal
b = 0b1010 # Binary (output: 10)
c = 0o12 # Octal (output: 10)
d = 0xFF # Hexadecimal (output: 255)

print(a, b, c, d) # Output: 42 10 10 255

—4—
Floating-Point Literals:

pi = 3.14159
price = 19.99
scientific = 1.5e-3 # 0.0015

print(pi, price, scientific)


# Output: 3.14159 19.99 0.0015

Boolean Literals:

is_student = True
is_employed = False

print(is_student, is_employed)
# Output: True False

Special Literal - None:

result = None # Represents absence of value


print(result) # Output: None

3. VARIABLES AND IDENTIFIERS

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:

# Method 1: Separate assignments


x = 5
y = 10
z = 15

# Method 2: Simultaneous assignment


a, b, c = 5, 10, 15

# Method 3: Same value to multiple variables


p = q = r = 100

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:

name = "Alice" # ✅ Valid


_private = 10 # ✅ Valid (convention for private)
variable123 = 5 # ✅ Valid
MY_CONSTANT = 3.14 # ✅ Valid (convention for constants)

Invalid Identifiers:

123name = "Bob" # ❌ Starts with digit


my-var = 5 # ❌ Contains hyphen

—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

Definition: Symbols that perform operations on values.

Types of Operators

A. Arithmetic Operators

Operator Name Example Result

+ 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

print(f"Addition: {a + b}") # Output: 19


print(f"Subtraction: {a - b}") # Output: 11

—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

Operator Meaning Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 5 > 3 True

< Less than 5 < 3 False

>= Greater than or equal 5 >= 5 True

<= Less than or equal 3 <= 5 True

x = 10
y = 5

print(x == y) # Output: False


print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False

—8—
print(x >= y) # Output: True
print(x <= y) # Output: False

C. Logical Operators

Operator Meaning Example

and Returns True if both conditions are True a > 5 and b < 10

or Returns True if at least one condition is True a > 5 or b < 10

not Returns opposite of condition not (a > 5)

a = 15
b = 8

print(a > 10 and b > 5) # Output: True


print(a > 10 and b > 20) # Output: False
print(a > 10 or b > 20) # Output: True
print(not (a > 10)) # Output: False

D. Assignment Operators

Operator Example Equivalent

= 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

Operator Meaning Example

in Item exists in sequence 'a' in 'apple' → True

not in Item doesn’t exist 'z' in 'apple' → False

fruits = ['apple', 'banana', 'orange']


print('apple' in fruits) # Output: True
print('grape' in fruits) # Output: False
print('grape' not in fruits) # Output: True

5. EXPRESSIONS AND DATA TYPES

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)

Operator Precedence (Highest to Lowest): 1. ** (Exponentiation) 2. * , / , // , %


(Multiplication, Division, Floor, Modulus) 3. + , - (Addition, Subtraction) 4. < , <= , > ,
>= (Comparison) 5. == , != (Equality) 6. and (Logical AND) 7. or (Logical OR)

# 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.

A. Numeric Data Types


Integer (int):

age = 25
count = -10
binary = 0b1010 # 10 in decimal

print(type(age)) # Output: <class 'int'>


print(age, count, binary)

Float (float):

pi = 3.14159
temperature = -5.5
scientific = 2.5e-3 # 0.0025

print(type(pi)) # Output: <class 'float'>


print(pi, temperature, scientific)

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

B. String Data Type

name = "Alice"
message = 'Hello'
multi_line = """Line 1
Line 2
Line 3"""

print(type(name)) # Output: <class 'str'>

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

print(type(is_true)) # Output: <class 'bool'>

# 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

Output: print() Function


Basic Syntax:

print("Hello, World!")

Multiple Arguments:

name = "Alice"
age = 20
print("Name:", name, "Age:", age)
# Output: Name: Alice Age: 20

Separator and End Parameters:

# Default separator is space, default end is newline


print("A", "B", "C") # Output: A B C

# 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:

Method 1: f-strings (Recommended):

— 14 —
name = "Bob"
age = 30
height = 5.8

print(f"Name: {name}, Age: {age}, Height: {height}")


# Output: Name: Bob, Age: 30, Height: 5.8

# With formatting
pi = 3.14159
print(f"Pi = {pi:.2f}") # Output: Pi = 3.14

Method 2: format() method:

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

Input: input() Function


Basic Syntax:

name = input("Enter your name: ")


print(f"Hello, {name}!")

Example Session:

Enter your name: Alice


Hello, Alice!

Getting Numeric Input:

— 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:

name = input("Enter name: ")


age = int(input("Enter age: "))
height = float(input("Enter height: "))

print(f"{name} is {age} years old and {height}m tall")

7. COMPLETE PROGRAM EXAMPLES

Example 1: Simple Calculator

# Program to perform arithmetic operations


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")

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:

Enter first number: 10


Enter second number: 5
Enter operation (+, -, *, /): +
Result: 15.0

Example 2: Area and Perimeter Calculator

import math

# Calculate area and perimeter of circle


radius = float(input("Enter radius of circle: "))

area = [Link] * radius ** 2


perimeter = 2 * [Link] * radius

print(f"Area = {area:.2f}")
print(f"Perimeter = {perimeter:.2f}")

Sample Run:

Enter radius of circle: 5


Area = 78.50
Perimeter = 31.42

Example 3: Temperature Conversion

# Convert temperature from Celsius to Fahrenheit


celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32

print(f"{celsius}°C = {fahrenheit}°F")

— 17 —
Sample Run:

Enter temperature in Celsius: 25


25.0°C = 77.0°F

8. KEY CONCEPTS SUMMARY

Concept Description Example

Literal Fixed value in code 42 , "Hello" , True

Variable Named container for data name = "Alice"

Identifier Name of variable/function name , age , _private

Operator Symbol for operations + , - , == , and

Expression Values + operators 2 + 3 * 4

Data Type Category of data int , str , float , bool

9. IMPORTANT 5 & 10 MARK QUESTIONS

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'>

Q3: Explain operator precedence in Python.

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

Valid: name, _private, var123, MY_CONST


Invalid: 123var, my-var, class

Q5: Differentiate between input() and print() functions.

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:

1. NUMERIC DATA TYPES


- int: Whole numbers (-42, 0, 100)
- float: Decimal numbers (3.14, -5.5)
- complex: Complex numbers (3+4j)

2. STRING DATA TYPE


- Sequence of characters
- Operations: concatenation (+), repetition (*)
- Indexing and slicing supported

— 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

Full Program Example:


num_str = input("Enter a number: ")
num = int(num_str)
squared = num ** 2
print(f"Square = {squared}")

Sample Run:
Enter a number: 5
Square = 25

Q2: Create a program to demonstrate all arithmetic operators and their


precedence.

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: "))

# Display with different formatting styles


print("\n--- OUTPUT FORMATTING STYLES ---\n")

# 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

--- OUTPUT FORMATTING STYLES ---

Name: Alice
Age: 25
Salary: $50000.00

Using format():
Name: Alice, Age: 25, Salary: $50000.00

Using concatenation:
Name: Alice, Age: 25

Alice is 25 years old with salary of $50000.00

Q4: Develop a program to calculate Simple Interest and demonstrate type


conversion.

Answer:
Program:
# Simple Interest = (Principal * Rate * Time) / 100

print("=== SIMPLE INTEREST CALCULATOR ===\n")

# Get inputs (input() returns string)


principal_str = input("Enter Principal Amount ($): ")
rate_str = input("Enter Rate of Interest (%): ")
time_str = input("Enter Time (years): ")

# Type conversion (string to float)


principal = float(principal_str)
rate = float(rate_str)
time = float(time_str)

— 23 —
# Calculation
simple_interest = (principal * rate * time) / 100
total_amount = principal + simple_interest

# Display results with formatting


print("\n--- RESULTS ---")
print(f"Principal: ${principal:.2f}")
print(f"Rate: {rate}%")
print(f"Time: {time} years")
print(f"Simple Interest: ${simple_interest:.2f}")
print(f"Total Amount: ${total_amount:.2f}")

Sample Run:
=== SIMPLE INTEREST CALCULATOR ===

Enter Principal Amount ($): 10000


Enter Rate of Interest (%): 5
Enter Time (years): 3

--- RESULTS ---


Principal: $10000.00
Rate: 5.0%
Time: 3.0 years
Simple Interest: $1500.00
Total Amount: $11500.00

Q5: Explain the difference between comparison operators and logical


operators with a program.

Answer:
COMPARISON OPERATORS: Compare two values, return boolean
- == (equal), != (not equal)
- > (greater), < (less)
- >= (greater or equal), <= (less or equal)

LOGICAL OPERATORS: Combine boolean values


- and: True if both are True
- or: True if at least one is True
- not: Negates boolean value

— 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

=== LOGICAL OPERATORS ===


(15 > 10) and (8 > 5): True
(15 > 10) and (8 > 10): False
(15 > 20) or (8 > 5): True
not (15 > 20): True

— 25 —
UNIT II: CONTROL STRUCTURES

1. INTRODUCTION TO 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

Definition: Expressions that evaluate to True or False.

Simple 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

Boolean Truth Table:

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

if age >= 18:

— 28 —
print("You are an adult")

# Output: You are an adult

Example 2: if with multiple statements

score = 85

if score >= 80:


print("Grade: A")
print("Excellent performance!")
print("Keep it up!")

# Output:
# Grade: A
# Excellent performance!
# Keep it up!

The if-else Statement


Syntax:

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 age >= 18:


print("You can vote")
else:
print("Too young to vote")

# Output: Too young to vote

The if-elif-else Statement


Syntax:

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

Example: Grade Assignment

score = 75

if score >= 90:


grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'

print(f"Score: {score}, Grade: {grade}")


# Output: Score: 75, Grade: C

4. INDENTATION IN PYTHON

Definition: Whitespace at the beginning of a line that defines code blocks.

— 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:

# ❌ ERROR: Missing indentation


if age >= 18:
print("Adult") # IndentationError!

# ❌ ERROR: Inconsistent indentation


if age >= 18:
print("Adult")
print("Vote") # IndentationError!

Standard Practice: Use 4 spaces for each indentation level.

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

Definition: Selecting among multiple options based on different conditions.

— 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"

print(get_day_name(3)) # Output: Wednesday

Nested if Statements

age = 25
income = 50000

if age >= 18:


if income > 30000:
print("Eligible for loan")
else:
print("Need higher income")
else:
print("Too young for loan")

# Output: Eligible for loan

— 33 —
Example: Nested Multi-way Selection

marks = 85

if marks >= 60:


if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
else:
print("Grade: C")
else:
print("Grade: F - Failed")

# Output: Grade: A

6. ITERATIVE CONTROL

The while Statement


Syntax:

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

Example 1: Simple while Loop

count = 1

while count <= 5:


print(f"Count: {count}")
count += 1

# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5

Example 2: Sum of Numbers

num = 1
total = 0

while num <= 10:


total += num
num += 1

print(f"Sum of 1 to 10: {total}") # Output: Sum of 1 to 10: 55

— 35 —
Infinite Loops
Definition: A loop that never ends because the condition is always True.

# ❌ INFINITE LOOP - DON'T RUN


count = 1
while True:
print(count)
# Missing: count += 1 (condition never becomes False)

Safe Infinite Loop with break:

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

Definite vs Indefinite Loops

Definite Loop Indefinite Loop

Known iterations Unknown iterations

for range(n) while condition

Fixed repetitions Until condition met

# Definite: Know it runs 5 times


for i in range(5):
print(i)

# Indefinite: Don't know how many runs

— 36 —
count = 1
while count < 10:
if some_condition():
break
count += 1

Boolean Flag
Definition: A Boolean variable used to control loop execution.

# Example: Search for a number


numbers = [3, 7, 2, 9, 5, 1]
target = 9
found = False
index = 0

while not found and index < len(numbers):


if numbers[index] == target:
found = True
print(f"Found {target} at index {index}")
index += 1

if not found:
print(f"{target} not found")

# Output: Found 9 at index 3

Example 2: User Input Validation

valid_input = False

while not valid_input:


age = int(input("Enter age (0-120): "))

if 0 <= age <= 120:


valid_input = True
print(f"Valid age: {age}")
else:
print("Invalid age, try again")

— 37 —
# Output:
# Enter age (0-120): 150
# Invalid age, try again
# Enter age (0-120): 25
# Valid age: 25

7. STRINGS, LISTS, AND DICTIONARIES

String Manipulation
String Creation:

s1 = "Hello"
s2 = 'World'
s3 = """Multi-line
String"""

print(s1, s2) # Output: Hello World

String Operations:

Operation Example Result

Length len("Hello") 5

Concatenation "Hello" + "World" “HelloWorld”

Repetition "Ha" * 3 “HaHaHa”

Indexing "Hello"[0] “H”

Slicing "Hello"[1:4] “ell”

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 = []

# List with values


list2 = [1, 2, 3, 4, 5]

# Mixed types
list3 = [1, "Hello", 3.14, True]

# Nested list
list4 = [[1, 2], [3, 4], [5, 6]]

List Operations:

numbers = [10, 20, 30, 40, 50]

# 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]

# Append (add to end)


[Link](60)
print(numbers) # Output: [10, 20, 30, 40, 50, 60]

# Insert at specific position


[Link](2, 25)
print(numbers) # Output: [10, 20, 25, 30, 40, 50, 60]

# Remove value
[Link](25)
print(numbers) # Output: [10, 20, 30, 40, 50, 60]

# Pop (remove by index)


value = [Link](0)
print(value) # Output: 10
print(numbers) # Output: [20, 30, 40, 50, 60]

# Membership check
print(30 in numbers) # Output: True
print(100 in numbers) # Output: False

List Iteration:

fruits = ["apple", "banana", "orange"]

for fruit in fruits:


print(fruit)

# Output:
# apple
# banana
# orange

— 40 —
Dictionary Manipulation
Definition: Collection of key-value pairs (unordered).

Dictionary Creation:

# Empty dictionary
dict1 = {}

# Dictionary with values


student = {
"name": "Alice",
"age": 20,
"grade": "A"
}

# 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

# Adding key-value pair


student["grade"] = "A"

# Modifying value
student["age"] = 21

# Deleting key-value pair

— 41 —
del student["city"]

# Checking key existence


if "name" in student:
print("Name exists") # Output: Name exists

# 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:

person = {"name": "Charlie", "age": 25, "city": "Boston"}

# Iterate over keys


for key in person:
print(f"{key}: {person[key]}")

# Output:
# name: Charlie
# age: 25
# city: Boston

# Better way - iterate over items


for key, value in [Link]():
print(f"{key}: {value}")

8. BUILDING BLOCKS OF PYTHON PROGRAMS

Typical Program Structure:

— 42 —
# 1. Import statements
import math
from datetime import datetime

# 2. Function definitions
def calculate_area(radius):
"""Calculate circle area"""
return [Link] * radius ** 2

# 3. Main program logic


if __name__ == "__main__":
# Get input
r = float(input("Enter radius: "))

# Process
area = calculate_area(r)

# Output
print(f"Area: {area:.2f}")

Program Flow Example:

# Program: Calculate factorial


def factorial(n):
result = 1
while n > 1:
result *= n
n -= 1
return result

# 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

9. UNDERSTANDING AND USING RANGES

Definition: range() generates sequence of numbers.

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

# Three arguments (with step)


for i in range(0, 10, 2):
print(i) # Output: 0 2 4 6 8

# Negative step (countdown)


for i in range(5, 0, -1):
print(i) # Output: 5 4 3 2 1

Converting range to list:

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]

With Lists - Indexed Iteration:

fruits = ["apple", "banana", "orange"]

# Without index
for fruit in fruits:
print(fruit)

# With index using range


for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")

# Output:
# 0: apple
# 1: banana
# 2: orange

10. BREAK AND CONTINUE STATEMENTS

break Statement
Definition: Exits the loop immediately.

for i in range(10):
if i == 5:
break
print(i)

# Output: 0 1 2 3 4

Example: Search and Exit

— 45 —
numbers = [3, 7, 2, 9, 5, 1, 8]
target = 9

for num in numbers:


print(f"Checking {num}")
if num == target:
print(f"Found {target}!")
break

# 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

Example: Skip Invalid Inputs

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

11. FOR LOOP

Syntax:

for variable in sequence:


# Code executes for each item
statement

Examples:

# Iterating over list


fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

# Iterating over string


for char in "Hello":
print(char)

# Iterating over range


for i in range(5):
print(i)

# Iterating with index


for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")

— 47 —
12. COMPLETE PROGRAM EXAMPLES

Example 1: Number Guessing Game

import random

# Program: Guess the number


target = [Link](1, 100)
guess = 0
attempts = 0

print("Guess the number between 1 and 100!")

while guess != target:


guess = int(input("Enter your guess: "))
attempts += 1

if guess < target:


print("Too low, try again!")
elif guess > target:
print("Too high, try again!")
else:
print(f"Correct! You won in {attempts} attempts!")

# 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!

Example 2: Grade Calculator

# Program: Calculate and assign grades


students = {
"Alice": 85,

— 48 —
"Bob": 92,
"Charlie": 78,
"Diana": 88,
"Eve": 65
}

print("=== GRADE REPORT ===\n")

for name, score in [Link]():


if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'

print(f"{name:10} | Score: {score:3} | Grade: {grade}")

# 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

Example 3: List Operations

# Program: Manage a shopping list


shopping_list = []

while True:
print("\n=== SHOPPING LIST ===")
print("1. Add item")
print("2. Remove item")

— 49 —
print("3. View list")
print("4. Exit")

choice = input("Enter choice (1-4): ")

if choice == '1':
item = input("Enter item to add: ")
shopping_list.append(item)
print(f"Added: {item}")

elif choice == '2':


item = input("Enter item to remove: ")
if item in shopping_list:
shopping_list.remove(item)
print(f"Removed: {item}")
else:
print("Item not found")

elif choice == '3':


if shopping_list:
print("\nItems:")
for i, item in enumerate(shopping_list, 1):
print(f"{i}. {item}")
else:
print("List is empty")

elif choice == '4':


print("Goodbye!")
break

else:
print("Invalid choice")

# Sample run shown in interaction

— 50 —
13. KEY CONCEPTS SUMMARY

Concept Purpose Example

if Execute code if condition is True if age >= 18:

elif Alternative condition elif score >= 80:

else Execute if all conditions are False else: print("Error")

while Loop while condition is True while count < 10:

for Loop through sequence for i in range(5):

break Exit loop if i == 5: break

continue Skip to next iteration if i % 2: continue

Boolean True/False value is_valid = True

14. IMPORTANT 5 & 10 MARK QUESTIONS

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

for loop: Repeats for each item in sequence


- Known number of iterations

— 51 —
- Used for definite loops
- Automatically iterates through sequence
Example:
for i in range(5):
print(i)

Both output: 0 1 2 3 4

Q2: What is a Boolean flag and how is it used?

Answer:
A Boolean flag is a Boolean variable (True/False) used to control
program flow.

Purpose: Control loop execution or program decisions

Example:
found = False
numbers = [3, 5, 7, 9]

for num in numbers:


if num == 7:
found = True
break

if found:
print("Number found")
else:
print("Number not found")

Q3: Explain string, list, and dictionary with examples.

Answer:
1. STRING: Sequence of characters
name = "Alice"
name[0] = 'A'
name[1:4] = 'lic'

2. LIST: Ordered collection (mutable)


numbers = [1, 2, 3, 4, 5]
[Link](6)

— 52 —
numbers[0] = 10

3. DICTIONARY: Key-value pairs


student = {"name": "Alice", "age": 20}
student["grade"] = "A"
student["name"] → "Alice"

Q4: What is indentation and why is it important in Python?

Answer:
Indentation is the whitespace at the beginning of a line that
defines code blocks in Python.

Why important: Python uses indentation instead of braces to define


scope (blocks). Incorrect indentation causes IndentationError.

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)

Standard: Use 4 spaces per indentation level

Q5: Explain break and continue statements with examples.

Answer:
break: Exits loop immediately
Example:
for i in range(10):
if i == 5:
break
print(i)
Output: 0 1 2 3 4

continue: Skips to next iteration


Example:
for i in range(5):
if i == 2:
continue

— 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: "))

# Find maximum using if-elif-else


if num1 >= num2 and num1 >= num3:
maximum = num1
print(f"Maximum: {maximum}")
elif num2 >= num1 and num2 >= num3:
maximum = num2
print(f"Maximum: {maximum}")
else:
maximum = num3
print(f"Maximum: {maximum}")

Sample Run:
Enter first number: 10
Enter second number: 25
Enter third number: 15
Maximum: 25

Q2: Create a program using while loop to display multiplication table.

Answer:
Program:
# Get number from user
num = int(input("Enter number for multiplication table: "))

# Display multiplication table using while loop


multiplier = 1

— 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")

choice = input("Enter choice: ")

if choice == '1':
item = input("Enter item to add: ")
[Link](item)
print(f"Added: {item}")

elif choice == '2':

— 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")

elif choice == '3':


if items:
print("\nCurrent items:")
for i, item in enumerate(items, 1):
print(f"{i}. {item}")
else:
print("List is empty")

elif choice == '4':


print("Exiting...")
break

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)

Q4: Create a program using dictionary to store and retrieve student


information.

— 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")

choice = input("Enter choice: ")

if choice == '1':
roll_no = input("Enter roll number: ")
name = input("Enter name: ")
marks = float(input("Enter marks: "))

students[roll_no] = {"name": name, "marks": marks}


print(f"Student added successfully")

elif choice == '2':


roll_no = input("Enter roll number: ")

if roll_no in students:
info = students[roll_no]
print(f"Name: {info['name']}, Marks: {info['marks']}")
else:
print("Student not found")

elif choice == '3':


if students:
print("\n=== ALL STUDENTS ===")
for roll, info in [Link]():
print(f"Roll: {roll}, Name: {info['name']}, Marks: {info['marks']}")
else:
print("No students found")

elif choice == '4':


print("Exiting...")

— 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)

Q5: Write nested if statements program to check triangle type.

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: "))

# Check if valid triangle


if a + b > c and b + c > a and a + c > b:
# Valid triangle, check type
if a == b == c:
print("Equilateral triangle")
elif a == b or b == c or a == c:
print("Isosceles triangle")
else:
print("Scalene triangle")
else:
print("Not a valid triangle")

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

Definition: Named blocks of code designed to perform specific tasks.

Benefits: - ✅ Code reusability - ✅ Modular design - ✅ Easier to debug - ✅ Better


organization - ✅ Reduced code duplication

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

Example 1: Simple Function

— 60 —
def greet():
"""Greet the user"""
print("Hello, Welcome!")

# Call the function


greet()
# Output: Hello, Welcome!

Example 2: Function with Parameters

def add(a, b):


"""Add two numbers"""
sum_result = a + b
return sum_result

# Call function
result = add(5, 3)
print(f"Sum: {result}") # Output: Sum: 8

Example 3: Multiple Parameters

def area_of_rectangle(length, width):


"""Calculate area of rectangle"""
area = length * width
return area

# Using function
result = area_of_rectangle(10, 5)
print(f"Area: {result}") # Output: Area: 50

Function Components:

Component Purpose Example

def Keyword to define function def greet():

function_name Name of function greet , add , calculate

parameters Inputs to function a, b

— 61 —
Component Purpose Example

docstring Documentation """Add two numbers"""

body Code to execute sum = a + b

return Return value return sum

3. CALLING VALUE-RETURNING FUNCTIONS

Definition: Functions that return a value to the caller.

Syntax:

result = function_name(arguments)

Example 1: Return Single Value

def square(num):
"""Return square of number"""
return num ** 2

result = square(5)
print(result) # Output: 25

Example 2: Return Multiple Values

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

Example 3: Using Return Value in Expression

— 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

4. CALLING NON-VALUE-RETURNING FUNCTIONS

Definition: Functions that perform actions but don’t return values.

Example 1: Print Function

def display_message(message):
"""Display a message"""
print(f"Message: {message}")

display_message("Hello, Python!")
# Output: Message: Hello, Python!

Example 2: Modifying External Variable

count = 0

def increment():
"""Increment count"""
global count
count += 1
print(f"Count: {count}")

increment() # Output: Count: 1


increment() # Output: Count: 2

Example 3: Multiple Actions

— 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

Definition: Methods of passing arguments to functions.

Pass by Value (Immutable Types)

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

Explanation: Integer is immutable, so changes inside function don’t affect original.

— 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]

Explanation: Lists are mutable, changes affect original list.

Immutable vs Mutable Types:

Immutable Mutable

int, float, str, tuple, bool list, dict, set

Changes inside function don’t affect original Changes inside function affect original

6. KEYWORD ARGUMENTS IN PYTHON

Definition: Passing arguments by name rather than position.

Example 1: Positional vs Keyword

def person_info(name, age, city):


"""Display person information"""
print(f"Name: {name}, Age: {age}, City: {city}")

# Positional arguments (order matters)


person_info("Alice", 25, "New York")

— 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

Example 2: Using Keyword Arguments

def calculate(a, b, operation="add"):


"""Calculate based on operation"""
if operation == "add":
return a + b
elif operation == "multiply":
return a * b
else:
return None

print(calculate(5, 3)) # Output: 8 (default)


print(calculate(5, 3, operation="multiply")) # Output: 15

7. DEFAULT ARGUMENTS IN PYTHON

Definition: Arguments with default values if not provided.

Syntax:

def function_name(parameter=default_value):
pass

Example 1: Single Default Argument

— 66 —
def greet(name="Guest"):
"""Greet with name"""
print(f"Hello, {name}!")

greet() # Output: Hello, Guest!


greet("Alice") # Output: Hello, Alice!

Example 2: Multiple Default Arguments

def create_profile(name, age=18, city="Unknown"):


"""Create user profile"""
print(f"Name: {name}, Age: {age}, City: {city}")

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

Example 3: Default with Different Types

def process_data(name, items=None, count=0, active=True):


"""Process data with defaults"""
if items is None:
items = []

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

Definition: Region where a variable is accessible.

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

Accessing Global from Local

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:

global_var = "I'm global"

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

9. RECURSION: RECURSIVE FUNCTIONS

Definition: A function that calls itself to solve a problem.

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

print(factorial_iterative(5)) # Output: 120

With Recursion:

def factorial(n):
"""Calculate factorial using recursion"""
# Base case
if n <= 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

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

Example 2: Fibonacci Series

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)

# Print first 10 Fibonacci numbers


for i in range(10):
print(fibonacci(i), end=" ")

# Output: 0 1 1 2 3 5 8 13 21 34

Example 3: Sum of Numbers

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

Example 4: Power Function

def power(base, exponent):


"""Calculate base^exponent recursively"""
# Base case
if exponent == 0:
return 1
# Recursive case
else:
return base * power(base, exponent - 1)

print(power(2, 5)) # Output: 32 (2^5)

Recursion vs Iteration:

— 72 —
Aspect Recursion Iteration

Code More elegant More efficient

Memory More (call stack) Less

Performance Slower Faster

Readability Complex Simple

When to use Natural problems Repetitive tasks

10. COMPLETE FUNCTION EXAMPLES

Example 1: Temperature Converter

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

for i in range(2, int(num**0.5) + 1):


if num % i == 0:
return False
return True

# 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

Example 3: GCD (Greatest Common Divisor)

def gcd(a, b):


"""Find GCD using recursion (Euclidean algorithm)"""
if b == 0:
return a
else:
return gcd(b, a % b)

# Test

— 74 —
print(gcd(48, 18)) # Output: 6
print(gcd(100, 50)) # Output: 50

Example 4: Palindrome Checker

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

11. KEY CONCEPTS SUMMARY

Concept Purpose Example

Function Reusable code block def add(a, b):

Parameter Input to function def func(x, y):

Argument Value passed to function func(5, 3)

Return Output from function return result

Scope Variable accessibility global, local

— 75 —
Concept Purpose Example

Recursion Function calls itself factorial(n-1)

12. IMPORTANT 5 & 10 MARK QUESTIONS

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

result = add(5, 3) # Reusable code

Q2: Explain the difference between parameters and arguments.

— 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}")

greet("Alice", 25) # "Alice", 25 are ARGUMENTS


greet("Bob", 30) # "Bob", 30 are ARGUMENTS

Q3: What is variable scope? Explain with example.

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

Q4: What is recursion? Explain with factorial example.

Answer:
Recursion: A function that calls itself.

Two essential parts:


1. Base case: Stops recursion (n <= 1)
2. Recursive case: Function calls itself with simpler input

— 77 —
Factorial Example:
def factorial(n):
if n <= 1: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)

factorial(5) = 5 * factorial(4) = ... = 120

Q5: Explain default arguments with example.

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}!")

greet() # Uses default: Hello, Guest!


greet("Alice") # Overrides default: Hello, Alice!

Another Example:
def describe(name, age=18, city="Unknown"):
print(f"{name}, {age}, {city}")

describe("Bob") # Bob, 18, Unknown


describe("Charlie", 25) # Charlie, 25, Unknown
describe("Diana", 30, "Boston") # Diana, 30, Boston

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

def compound_interest(principal, rate, time):


"""Calculate compound interest"""
amount = principal * ((1 + rate/100) ** time)
ci = amount - principal
return ci

def display_results(principal, rate, time):


"""Display both interests"""
si = simple_interest(principal, rate, time)
ci = compound_interest(principal, rate, time)

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): "))

display_results(principal, rate, time)

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

Q2: Create a program with recursive function to generate Fibonacci series.

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 calculate_area(length, width):


"""Calculate rectangle area - local variables"""
area = length * width
perimeter = 2 * (length + width)
return area, perimeter

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")

print("Initial global counter:", global_counter)

increment_global()
increment_global()
print("After incrementing:", global_counter)

area, perimeter = calculate_area(10, 5)


print(f"\nRectangle: Area = {area}, Perimeter = {perimeter}")

process_data()

if __name__ == "__main__":
main()

— 81 —
Sample Output:
=== SCOPE DEMONSTRATION ===

Initial global counter: 0


After incrementing: 2

Rectangle: Area = 50, Perimeter = 30

Local variable: 100


Global counter: 2

Q4: Create functions for string operations - palindrome, vowels, reverse.

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

Q5: Write program to demonstrate keyword and default arguments.

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")

def print_record(name, roll_no, stream="Commerce", marks=85):


"""Print record using keyword arguments"""
percentage = (marks / 100) * 100
print(f"Record of {name}")
print(f"Roll: {roll_no}, Stream: {stream}, Marks: {marks}%\n")

# Main program
print("=== POSITIONAL ARGUMENTS ===")
create_student_record("Alice", 101)
create_student_record("Bob", 102, "Commerce")

print("=== KEYWORD ARGUMENTS ===")


create_student_record(name="Charlie", roll_no=103,
stream="Biology", grade="B", marks=75)

print("=== MIXED ARGUMENTS ===")


print_record("Diana", 104, marks=92)

— 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

=== KEYWORD ARGUMENTS ===


Name: Charlie
Roll No: 103
Stream: Biology
Grade: B
Marks: 75

=== MIXED ARGUMENTS ===


Record of Diana
Roll: 104, Stream: Science, Marks: 92%

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() │
└──────────────────────┘

Example: Creating a Simple Object

# Define a class
class Dog:
def __init__(self, name, age):
[Link] = name # Attribute
[Link] = age # Attribute

def bark(self): # Method


print(f"{[Link]} says Woof!")

— 85 —
def get_age(self): # Method
return [Link]

# Create objects (instances)


dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# 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

Definition: Graphics module for creating drawings using a virtual turtle.

Installation: Built-in with Python (part of turtle module)

Basic Turtle Commands:

Command Purpose Example

[Link](distance) Move forward [Link](100)

[Link](distance) Move backward [Link](50)

[Link](angle) Turn right [Link](90)

[Link](angle) Turn left [Link](45)

— 86 —
Command Purpose Example

[Link]() Lift pen (no draw) [Link]()

[Link]() Put pen down (draw) [Link]()

[Link](width) Change pen width [Link](5)

[Link](color) Change pen color [Link]("red")

[Link](color) Change fill color [Link]("blue")

turtle.begin_fill() Start filling turtle.begin_fill()

turtle.end_fill() End filling turtle.end_fill()

[Link](radius) Draw circle [Link](50)

[Link](size, color) Draw dot [Link](10, "red")

[Link](x, y) Go to position [Link](100, 50)

[Link]() Stamp at current position [Link]()

[Link](shape) Change turtle shape [Link]("arrow")

Example 1: Drawing a Square

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]()

Example 2: Drawing a Circle and Dot

import turtle

[Link](0)

# Draw circle
[Link]("blue")
[Link](100)

# Draw dot
[Link]()
[Link](0, -100)
[Link]()
[Link](20, "red")

[Link]()
[Link]()

Example 3: Drawing Polygon

import turtle

def draw_polygon(sides, size):


"""Draw a polygon with given sides"""
angle = 360 / sides
for i in range(sides):
[Link](size)
[Link](angle)

# Draw multiple polygons


[Link](2)

for i in range(3, 9): # Triangles to octagons


[Link](["red", "blue", "green", "yellow", "orange", "purple"][i-3])
draw_polygon(i, 100)

— 88 —
[Link]()
[Link](150)
[Link]()

[Link]()
[Link]()

Example 4: Spiral Design

import turtle

[Link](0)
[Link]("blue")

for i in range(36):
[Link](i * 5)
[Link](10)

[Link]()
[Link]()

3. TURTLE ATTRIBUTES

Turtle Attributes (Properties and Methods):

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

Complete Attributes Example:

import turtle

screen = [Link]()
t = [Link]()

# Set attributes
[Link](2)
[Link](3)
[Link]("red")
[Link]("arrow")

# Draw and display attributes


[Link](100)
print(f"Position: {[Link]()}")
print(f"Heading: {[Link]()}")
print(f"Speed: {[Link]()}")
print(f"Pen color: {[Link]()}")
print(f"Pen width: {[Link]()}")

— 90 —
# Rotate
[Link](45)
[Link](50)

[Link]()

4. MODULAR DESIGN

Definition: Breaking program into independent, reusable modules.

Benefits: - ✅ Easy to understand - ✅ Easy to test - ✅ Easy to maintain - ✅ Code reuse - ✅


Team collaboration

Modular Program Structure:

┌───────────────────────────┐
│ MAIN PROGRAM │
├───────────────────────────┤
│ Module 1 │ Module 2 │
│ ───────── │ ───────── │
│ - Func A │ - Func C │
│ - Func B │ - Func D │
└───────────────────────────┘

Example: Modular Calculator

# Module 1: Arithmetic operations


def add(a, b):
return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):

— 91 —
if b != 0:
return a / b
else:
return "Cannot divide by zero"

# Module 2: Display functions


def display_menu():
print("\n=== CALCULATOR ===")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

def get_numbers():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
return a, b

# Module 3: Main logic


def main():
while True:
display_menu()
choice = input("Choose operation: ")

if choice == '5':
print("Goodbye!")
break

if choice in ['1', '2', '3', '4']:


a, b = get_numbers()

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

Definition: Files containing Python code (functions, classes, variables).

Built-in Modules:

import math
import random
import datetime
from turtle import Turtle

Module Usage:

# Method 1: Import entire module


import math
result = [Link](16)
print(result) # Output: 4.0

# Method 2: Import specific function


from math import sqrt, pi
result = sqrt(16)
print(pi) # Output: 3.14159...

# Method 3: Import with alias


import numpy as np
# Use: [Link]()

Common Built-in Modules:

Module Purpose Examples

math Math operations [Link]() , [Link]()

— 93 —
Module Purpose Examples

random Random numbers [Link]() , [Link]()

datetime Date/time [Link]() , date()

string String operations string.ascii_letters

os Operating system [Link]() , [Link]()

6. TOP-DOWN DESIGN

Definition: Breaking problem into progressively smaller subproblems.

Process:

┌─────────────────────────────────┐
│ MAIN PROBLEM │
└────────────────────┬────────────┘

┌────────────┼────────────┐
│ │ │
┌───V───┐ ┌───V───┐ ┌───V────┐
│Module1│ │Module2│ │Module3 │
└───┬───┘ └───┬───┘ └────┬───┘
│ │ │
┌───V───┐ ┌───V────┐ ┌────V────┐
│Task 1 │ │Task 2 │ │Task 3 │
│Task 2 │ │Task 3 │ │Task 4 │
└───────┘ └────────┘ └─────────┘

Example: Bank Management System

# Top-Level: Main System


def bank_system():
while True:
print("\n=== BANK SYSTEM ===")
print("1. Account Management")
print("2. Transactions")

— 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

# Module 1: Account Management


def account_management():
print("\n=== ACCOUNT MANAGEMENT ===")
print("1. Create Account")
print("2. Delete Account")

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

Creating Custom Modules:

File: math_operations.py

def add(a, b):


"""Add two numbers"""
return a + b

def multiply(a, b):


"""Multiply two numbers"""
return a * b

PI = 3.14159

File: [Link]

from math_operations import add, multiply, PI

# Using custom module


result1 = add(5, 3)
result2 = multiply(4, 6)

print(f"Sum: {result1}")
print(f"Product: {result2}")
print(f"Pi: {PI}")

# Output:
# Sum: 8

— 96 —
# Product: 24
# Pi: 3.14159

8. KEY CONCEPTS SUMMARY

Concept Purpose Example

Object Instance of class dog = Dog("Buddy")

Class Blueprint for objects class Dog:

Attribute Object property [Link]

Method Object function def bark(self):

Module Code file/package import turtle

Turtle Graphics module [Link](100)

9. IMPORTANT 5 & 10 MARK QUESTIONS

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)

[Link]() # Calls method


[Link]()

Output:
Alice - 101
Bob - 102

Q2: Explain modular design and its benefits.

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

Q3: What is turtle graphics? List basic commands.

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

Q4: What are modules in Python? Give examples.

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

Q5: Explain top-down design with example.

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 deposit(self, amount):


"""Add money to account"""
if amount > 0:
[Link] += amount
print(f"Deposited: ${amount:.2f}")
return True
else:
print("Invalid amount")
return False

def withdraw(self, amount):


"""Remove money from account"""
if amount > 0 and amount <= [Link]:
[Link] -= amount
print(f"Withdrew: ${amount:.2f}")
return True
else:
print("Insufficient balance or invalid amount")
return False

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

Q2: Write a program using turtle graphics to draw a house.

Answer:
Program:
import turtle

def draw_square(t, size, color):


"""Draw filled square"""
[Link](color)
t.begin_fill()
for i in range(4):

— 101 —
[Link](size)
[Link](90)
t.end_fill()

def draw_triangle(t, size, color):


"""Draw filled triangle (roof)"""
[Link](color)
t.begin_fill()
for i in range(3):
[Link](size)
[Link](120)
t.end_fill()

def draw_house():
"""Draw complete house"""
screen = [Link]()
[Link]("House")

t = [Link]()
[Link](1)

# Draw roof (triangle)


[Link]()
[Link](-75, 100)
[Link]()
[Link]("brown")
[Link](2)
draw_triangle(t, 150, "red")

# Draw walls (square)


[Link]()
[Link](-75, 100)
[Link]()
draw_square(t, 150, "lightblue")

# 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()

UNIT V: DICTIONARIES, SETS,


AND FILE HANDLING

1. DICTIONARY TYPE IN PYTHON

Definition: Unordered collection of key-value pairs (mutable).

Dictionary Creation:

# Method 1: Empty dictionary


dict1 = {}

# Method 2: With values


student = {
"name": "Alice",
"age": 20,

— 103 —
"grade": "A",
"city": "New York"
}

# Method 3: Using dict()


dict3 = dict(name="Bob", age=25)

# Method 4: Using fromkeys


dict4 = [Link](["a", "b", "c"], 0)
print(dict4) # {'a': 0, 'b': 0, 'c': 0}

Dictionary Operations:

student = {"name": "Alice", "age": 20, "city": "Boston"}

# 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")

# Getting all keys, values, items


print([Link]()) # dict_keys(['name', 'age', ...])
print([Link]()) # dict_values(['Alice', 21, ...])
print([Link]()) # dict_items([('name', 'Alice'), ...])

# Dictionary length
print(len(student)) # 2

— 104 —
# Clearing dictionary
[Link]() # Empty dictionary

Dictionary Methods:

Method Purpose Example

get(key, default) Get value safely [Link]("key", "default")

keys() Get all keys [Link]()

values() Get all values [Link]()

items() Get key-value pairs [Link]()

pop(key) Remove and return [Link]("key")

update() Merge dictionaries [Link](dict2)

clear() Empty dictionary [Link]()

copy() Make copy dict2 = [Link]()

Dictionary Iteration:

person = {"name": "Charlie", "age": 30, "city": "Boston"}

# Iterate keys
for key in person:
print(key)

# Iterate key-value pairs


for key, value in [Link]():
print(f"{key}: {value}")

# Iterate values only


for value in [Link]():
print(value)

# 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"}
}
}

# Access nested values


print(school["students"]["001"]["name"]) # Output: Alice
print(school["teachers"]["T001"]["subject"]) # Output: Math

2. SET DATA TYPE

Definition: Unordered collection of unique, immutable items.

Set Creation:

# Method 1: Using braces


set1 = {1, 2, 3, 4, 5}

# Method 2: Using set()


set2 = set([1, 2, 2, 3, 3, 4]) # Duplicates removed
print(set2) # {1, 2, 3, 4}

— 106 —
# Method 3: Empty set
set3 = set() # Not {} which is dict

# Method 4: Set of strings


set4 = {"apple", "banana", "orange"}

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}

print(set_a.issubset(set_b)) # True (all of a in b)


print(set_b.issuperset(set_a)) # True (b contains all of a)
print(set_a.isdisjoint(set_c)) # True (no common elements)

Set vs List:

Set List

Unordered Ordered

Unique items Can have duplicates

Fast membership check Slower membership

Immutable items Any items

{1, 2, 3} [1, 2, 3]

3. OPENING TEXT FILES

File Modes:

Mode Purpose Description

'r' Read Read existing file (default)

'w' Write Overwrite file

'a' Append Add to end of file

'x' Create Create new file

'b' Binary Binary mode

't' Text Text mode (default)

— 108 —
Opening Files:

# Method 1: Basic file open


file = open("[Link]", "r")
# Use file
[Link]()

# Method 2: Using with statement (recommended)


with open("[Link]", "r") as file:
# Use file
pass # Automatically closes

Example:

# Open and read


with open("[Link]", "r") as file:
content = [Link]()
print(content)

4. READING TEXT FILES

Methods to Read:

# Method 1: read() - Read entire file


with open("[Link]", "r") as file:
content = [Link]()
print(content)

# Method 2: readline() - Read one line


with open("[Link]", "r") as file:
line1 = [Link]()
line2 = [Link]()
print(line1, line2)

# Method 3: readlines() - Read all lines as list


with open("[Link]", "r") as file:
lines = [Link]()

— 109 —
for line in lines:
print([Link]())

# Method 4: Iterate over file


with open("[Link]", "r") as file:
for line in file:
print([Link]())

# Method 5: With line numbers


with open("[Link]", "r") as file:
for i, line in enumerate(file, 1):
print(f"{i}: {[Link]()}")

Example Program:

# Read and display file


def read_file(filename):
"""Read and display file contents"""
try:
with open(filename, "r") as file:
print(f"Contents of {filename}:\n")
content = [Link]()
print(content)
except FileNotFoundError:
print(f"File {filename} not found")

read_file("[Link]")

5. WRITING TEXT FILES

Writing Methods:

# Method 1: write() - Single string


with open("[Link]", "w") as file:
[Link]("Hello, World!\n")
[Link]("Python is great!")

— 110 —
# Method 2: writelines() - Multiple strings
with open("[Link]", "w") as file:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
[Link](lines)

# Method 3: Append to file


with open("[Link]", "a") as file:
[Link]("\nAppended line")

Example Program:

# Write student data to file


def save_students(students, filename):
"""Save student data to file"""
with open(filename, "w") as file:
for student in students:
[Link](f"{student['name']},{student['roll']},{student['marks']}\n")

# 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

Definition: Handling errors gracefully without crashing program.

Exception Types:

Exception Cause Example

ValueError Invalid value int("abc")

— 111 —
Exception Cause Example

TypeError Wrong type "text" + 5

ZeroDivisionError Divide by zero 10 / 0

IndexError Invalid index list[10] when list has 5 items

KeyError Invalid dictionary key dict["missing"]

FileNotFoundError File not found open("[Link]")

IOError Input/Output error File operations

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")

Example 1: File Error Handling

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")

Example 2: Type Conversion Error

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")

Example 3: Multiple Error Types

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

Example 1: Student Records Management

import os

class StudentRecords:
def __init__(self, filename="[Link]"):
[Link] = filename

def add_student(self, name, roll, marks):


"""Add student record"""
try:
with open([Link], "a") as file:
[Link](f"{name},{roll},{marks}\n")
print(f"Student {name} added successfully")
except IOError:
print("Error: Cannot write to file")

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")

def search_student(self, name):


"""Search student by name"""
try:
with open([Link], "r") as file:
found = False
for line in file:
data = [Link]().split(",")
if data[0].lower() == [Link]():
print(f"Found: Name: {data[0]}, Roll: {data[1]}, Marks: {data[2]}")
found = True

— 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

8. KEY CONCEPTS SUMMARY

Concept Description Example

Dictionary Key-value pairs {"name": "Alice"}

Set Unique items {1, 2, 3}

— 115 —
Concept Description Example

File I/O File operations open() , read() , write()

Exception Error handling try-except

Mode File access type "r" , "w" , "a"

9. IMPORTANT 5 & 10 MARK QUESTIONS

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

Q2: What are sets? Explain with example.

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

Advantages: Fast membership check, remove duplicates

Q3: Explain file modes and how to open files.

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]()

Method 2: Recommended (with statement)


with open("[Link]", "r") as file:
content = [Link]()
# Automatically closes

Q4: What are exceptions? How to handle them?

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")

Q5: Explain dictionary vs set.

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

Use dictionary for: Related data (name, age, marks)


Use set for: Unique items, removing duplicates

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
}

print("=== DICTIONARY OPERATIONS ===\n")

# 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']}")

# Keys, values, items


print(f"\nKeys: {list([Link]())}")
print(f"Values: {list([Link]())}")
print(f"Total keys: {len(employee)}")

Sample Output:

— 119 —
=== DICTIONARY OPERATIONS ===

Original dictionary:
id: 101
name: Alice
department: IT
salary: 50000
years: 5

After adding location: Boston


Updated salary: 55000
Removed 'years' key
Employee name: Alice
Department: IT

Keys: ['id', 'name', 'department', 'salary', 'location']


Values: [101, 'Alice', 'IT', 55000, 'Boston']
Total keys: 5

Q2: Create program for set operations and removing duplicates.

Answer:
Program:
# Create sets
numbers1 = {1, 2, 3, 4, 5}
numbers2 = {3, 4, 5, 6, 7}

print("=== SET OPERATIONS ===\n")

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}")

# Remove duplicates from list


data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique = list(set(data))
print(f"\nOriginal list: {data}")
print(f"After removing duplicates: {unique}")

# 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}

Original list: [1, 2, 2, 3, 3, 3, 4, 5, 5]


After removing duplicates: [1, 2, 3, 4, 5]

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]:

1: Product Price Quantity


2: Laptop $999 5
3: Mouse $25 20
4: Keyboard $75 15
Total lines: 4
Data appended to [Link]

Contents of [Link]:

1: Product Price Quantity


2: Laptop $999 5
3: Mouse $25 20
4: Keyboard $75 15
5: Monitor $300 8

Q4: Create program with exception handling for file operations.

Answer:
Program:
def safe_file_operation():

— 123 —
"""Demonstrate exception handling in file operations"""

# Operation 1: Read file


try:
with open("[Link]", "r") as file:
content = [Link]()
print("File read successfully")
except FileNotFoundError:
print("Error: File not found")
except IOError:
print("Error: Cannot read file")

# Operation 2: Convert input


try:
age = int(input("Enter age: "))
if 0 < age < 150:
print(f"Valid age: {age}")
else:
raise ValueError("Age must be between 0 and 150")
except ValueError as e:
print(f"Error: {e}")

# Operation 3: List access


try:
numbers = [1, 2, 3]
index = int(input("Enter index: "))
print(f"Value: {numbers[index]}")
except IndexError:
print("Error: Index out of range")
except ValueError:
print("Error: Invalid index")

# Operation 4: Dictionary access


try:
student = {"name": "Alice", "age": 20}
key = input("Enter key: ")
value = student[key]
print(f"{key}: {value}")
except KeyError:
print(f"Error: Key not found")

# 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])

print(f"Name: {name:15} Roll: {roll:5} Marks: {marks}")


marks_list.append(marks)

— 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)

print(f"\n=== STATISTICS ===")


print(f"Total students: {len(marks_list)}")
print(f"Average marks: {avg:.2f}")
print(f"Maximum marks: {max_marks}")
print(f"Minimum marks: {min_marks}")

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")

# Create and process


create_sample_file()
process_csv_file("[Link]")

— 126 —
Sample Output:
Sample file created: [Link]

Reading file: [Link]

Header: Name,Roll,Marks

Name: Alice Roll: 101 Marks: 85.0


Name: Bob Roll: 102 Marks: 90.0
Name: Charlie Roll: 103 Marks: 78.0
Name: Diana Roll: 104 Marks: 92.0

=== STATISTICS ===


Total students: 4
Average marks: 86.25
Maximum marks: 92.0
Minimum marks: 78.0

File processing completed

FINAL SUMMARY AND REVISION

All 5 Units at a Glance

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 —

You might also like