0% found this document useful (0 votes)
30 views38 pages

Python Programming Guide for B.Tech Students

This document is a comprehensive guide on Python programming fundamentals and data structures aimed at undergraduate students. It covers essential topics such as the Python interpreter, basic structure, indentation, keywords, identifiers, functions, and recursion. The guide is structured into units, providing examples and explanations to facilitate learning for first-year B.Tech students at Woxsen University.

Uploaded by

pagal
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)
30 views38 pages

Python Programming Guide for B.Tech Students

This document is a comprehensive guide on Python programming fundamentals and data structures aimed at undergraduate students. It covers essential topics such as the Python interpreter, basic structure, indentation, keywords, identifiers, functions, and recursion. The guide is structured into units, providing examples and explanations to facilitate learning for first-year B.Tech students at Woxsen University.

Uploaded by

pagal
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 Guide for Undergraduate Students

Units IV & V

Unit IV: Python Fundamentals

Unit V: Data Structures & Files

Prepared for First Year [Link] Students


Woxsen
Generated: Univeristy
November 2025

Page 1 of 38
UNIT IV
Python Fundamentals

1. Python Interpreter
The Python interpreter is a program that reads and executes Python code. Python can be run
in two modes: interactive mode and script mode.

1.1 Interactive Mode


In interactive mode, you can type Python commands directly and see immediate results. This
is excellent for testing small code snippets and learning.

# Start Python interactive mode by typing 'python' or 'python3' in terminal


>>> 2 + 3
5
>>> print("Hello, Python!")
Hello, Python!
>>> x = 10
>>> x * 2
20

1.2 Script Mode


In script mode, you write Python code in a file (with .py extension) and execute it. This is used
for larger programs.

# File: [Link]
print("Hello, Python!")
print("This is script mode")
# Run from terminal: python [Link]
# Output:
# Hello, Python!
# This is script mode

Note: Python is an interpreted language, meaning code is executed line by line. This makes
debugging easier but can be slower than compiled languages like C.

Page 2 of 38
2. Basic Python Structure
Python programs consist of statements organized into logical blocks. A well-structured Python
program is easy to read and maintain.
# Basic structure of a Python program
# 1. Comments (for documentation)
# This is a single-line comment
"""
This is a multi-line comment
or docstring, used for documentation
"""
# 2. Import statements (at the top)
import math
from datetime import datetime
# 3. Constants and global variables
PI = 3.14159
GRAVITY = 9.8
# 4. Function definitions
def calculate_area(radius):
"""Calculate area of a circle"""
return PI * radius ** 2
# 5. Main program code
if __name__ == "__main__":
radius = 5
area = calculate_area(radius)
print(f"Area of circle: {area}")

3. Indentation
Python uses indentation (whitespace at the beginning of lines) to define code blocks. This is
unique to Python and makes code highly readable. Most other languages use curly braces {}.

3.1 Why Indentation Matters


# Correct indentation
if True:
print("This is indented")
print("Part of the if block")
print("This is not indented")
# Output:
# This is indented
# Part of the if block
# This is not indented
# WRONG - IndentationError
if True:
print("This will cause an error") # Missing indentation

3.2 Indentation Rules


Rule Description Example

Use 4 spaces Standard convention (not tabs) if x > 0:

Be consistent Same indentation in a block print(x)

Page 3 of 38
Nested blocks Increase indentation for each level if y > 0:

# Example: Nested indentation


def check_number(num):
if num > 0:
if num % 2 == 0:
print(f"{num} is positive and even")
else:
print(f"{num} is positive and odd")
else:
print(f"{num} is non-positive")
check_number(10) # Output: 10 is positive and even
check_number(7) # Output: 7 is positive and odd
check_number(-3) # Output: -3 is non-positive

Page 4 of 38
4. Python Concepts
4.1 Keywords
Keywords are reserved words in Python that have special meanings. You cannot use them as
variable names or identifiers.

False None True and as

assert break class continue def

del elif else except finally

for from global if import

in is lambda nonlocal not

or pass raise return try

while with yield

# Example: Using keywords


# 'if', 'else', 'for', 'in' are keywords
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
# WRONG - Cannot use keyword as variable name
# for = 5 # SyntaxError: invalid syntax

4.2 Identifiers
Identifiers are names given to variables, functions, classes, etc. They must follow specific
rules in Python.

Rule Valid Examples Invalid Examples

Start with letter or _ name, _value, MyClass 2name, $value

Contains letters, digits, _ var1, user_name user-name, [Link]

Case-sensitive age ≠ Age ≠ AGE

Cannot be keyword my_for, class_name for, class

# Valid identifiers
student_name = "Alice"
_private_var = 100
Course2024 = "Python Programming"
my_list = [1, 2, 3]

Page 5 of 38
# Naming conventions (not rules, but good practice)
CONSTANT_VALUE = 3.14159 # Constants: UPPERCASE
class_name = "[Link]" # Variables: lowercase with underscores
MyClass = "Example" # Classes: PascalCase
# Invalid identifiers (will cause errors)
# 2students = 10 # Starts with digit
# my-variable = 5 # Contains hyphen
# for = 10 # Keyword used as identifier

Page 6 of 38
4.3 Statements and Expressions
Statement: An instruction that Python can execute (does something).
Expression: A combination of values and operators that evaluates to a value.

# Expressions (evaluate to a value)


5 + 3 # Expression: evaluates to 8
x * 2 # Expression: evaluates to double of x
len("Hello") # Expression: evaluates to 5
x > 10 # Expression: evaluates to True or False
# Statements (perform an action)
x = 10 # Assignment statement
print("Hello") # Function call statement
if x > 5: # Conditional statement
print("Greater")
# Complex example
x = 10 # Statement
y = x * 2 + 5 # Statement with expression (x * 2 + 5)
result = (y > 20) # Statement with boolean expression
# Multi-line statements using backslash
total = 1 + 2 + 3 + \
4 + 5 + 6
# Multi-line statements using parentheses (preferred)
total = (1 + 2 + 3 +
4 + 5 + 6)
# Multiple statements on one line (not recommended)
x = 5; y = 10; print(x + y) # Semicolon separates statements

4.4 Basic Input and Output


Python provides simple functions for interacting with users through the console.

Output: print() function


# Basic print
print("Hello, World!")
# Print multiple items
print("Name:", "Alice", "Age:", 20)
# Print with separator
print("Python", "Java", "C++", sep=", ")
# Output: Python, Java, C++
# Print without newline
print("Loading", end="...")
print("Done!")
# Output: Loading...Done!
# Formatted strings (f-strings) - Python 3.6+
name = "Bob"
age = 21
print(f"My name is {name} and I am {age} years old")
# Format method
print("My name is {} and I am {} years old".format(name, age))
# Formatting numbers
pi = 3.14159265
print(f"Pi to 2 decimals: {pi:.2f}") # Output: Pi to 2 decimals: 3.14
print(f"Pi to 4 decimals: {pi:.4f}") # Output: Pi to 4 decimals: 3.1416

Input: input() function


# Basic input (always returns a string)

Page 7 of 38
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Input with type conversion
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print(f"Age: {age}, Height: {height}")
# Complete example: Simple calculator
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 == '/':
if num2 != 0:
result = num1 / num2
else:
result = "Error: Division by zero"
else:
result = "Invalid operation"
print(f"Result: {result}")

Important: input() always returns a string. Use int(), float(), etc. to convert to the required data
type.

Page 8 of 38
5. Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code,
avoid repetition, and make programs easier to understand.

5.1 Defining Functions


# Basic function definition
def greet():
"""This function prints a greeting"""
print("Hello, Welcome to Python!")
# Call the function
greet() # Output: Hello, Welcome to Python!
# Function with parameters
def greet_person(name):
"""Greet a person by name"""
print(f"Hello, {name}!")
greet_person("Alice") # Output: Hello, Alice!
greet_person("Bob") # Output: Hello, Bob!
# Function with multiple parameters
def add_numbers(a, b):
"""Add two numbers and print result"""
result = a + b
print(f"{a} + {b} = {result}")
add_numbers(5, 3) # Output: 5 + 3 = 8

5.2 Return Values


# Function with return value
def add(a, b):
"""Return the sum of two numbers"""
return a + b
result = add(10, 20)
print(f"Sum: {result}") # Output: Sum: 30
# Function returning multiple values
def calculate(a, b):
"""Return sum, difference, product, and quotient"""
return a + b, a - b, a * b, a / b
sum_val, diff, prod, quot = calculate(10, 5)
print(f"Sum: {sum_val}, Difference: {diff}")
print(f"Product: {prod}, Quotient: {quot}")
# Function with conditional return
def absolute_value(num):
"""Return absolute value of a number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(10)) # Output: 10
print(absolute_value(-7)) # Output: 7

5.3 Default Parameters


# Function with default parameter values
def power(base, exponent=2):
"""Calculate base raised to exponent (default: 2)"""
return base ** exponent
print(power(5)) # Uses default: 5^2 = 25
print(power(5, 3)) # Overrides default: 5^3 = 125

Page 9 of 38
# Multiple default parameters
def student_info(name, age=18, grade="A"):
"""Display student information"""
print(f"Name: {name}, Age: {age}, Grade: {grade}")
student_info("Alice") # Uses all defaults
student_info("Bob", 20) # Overrides age
student_info("Charlie", 19, "B") # Overrides both
student_info("Diana", grade="A+") # Keyword argument

5.4 Keyword Arguments


# Positional arguments
def describe_pet(animal, name):
print(f"I have a {animal} named {name}")
describe_pet("dog", "Buddy") # Positional
# Keyword arguments (order doesn't matter)
describe_pet(name="Whiskers", animal="cat")
describe_pet(animal="parrot", name="Polly")
# Mixing positional and keyword
def student_details(name, roll_no, age, course="[Link]"):
print(f"Name: {name}, Roll: {roll_no}, Age: {age}, Course: {course}")
student_details("Alice", 101, 19)
student_details("Bob", 102, age=20, course="[Link]")

Page 10 of 38
5.5 Variable-length Arguments
# *args - Variable number of positional arguments
def sum_all(*numbers):
"""Sum any number of arguments"""
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(10, 20, 30, 40)) # Output: 100
# **kwargs - Variable number of keyword arguments
def student_report(**details):
"""Print student details from keyword arguments"""
for key, value in [Link]():
print(f"{key}: {value}")
student_report(name="Alice", age=19, grade="A", city="Mumbai")
# Combining all types
def complex_function(pos1, pos2, *args, default_val=10, **kwargs):
print(f"Positional: {pos1}, {pos2}")
print(f"Extra positional: {args}")
print(f"Default: {default_val}")
print(f"Keyword args: {kwargs}")
complex_function(1, 2, 3, 4, 5, course="Python", level="Beginner")

5.6 Lambda Functions


Lambda functions are small anonymous functions defined using the lambda keyword. They
can have any number of arguments but only one expression.

# Regular function
def square(x):
return x ** 2
# Equivalent lambda function
square_lambda = lambda x: x ** 2
print(square(5)) # Output: 25
print(square_lambda(5)) # Output: 25
# Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 7)) # Output: 10
# Lambda in sorting
students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 18},
{"name": "Charlie", "age": 22}
]
# Sort by age using lambda
students_by_age = sorted(students, key=lambda s: s["age"])
print(students_by_age)
# Lambda with map() - apply function to all items
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
# Lambda with filter() - filter items
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]

5.7 Scope of Variables

Page 11 of 38
# Global variable
global_var = "I am global"
def my_function():
# Local variable
local_var = "I am local"
print(global_var) # Can access global
print(local_var) # Can access local
my_function()
print(global_var) # Can access global
# print(local_var) # Error: local_var not accessible outside function
# Modifying global variable
counter = 0
def increment():
global counter # Declare global to modify
counter += 1
print(f"Counter: {counter}")
increment() # Counter: 1
increment() # Counter: 2
print(counter) # Output: 2

Page 12 of 38
6. Recursion
Recursion is a programming technique where a function calls itself. Every recursive function
must have a base case (stopping condition) and a recursive case (where it calls itself).

6.1 Basic Recursion Example


# Factorial using recursion
def factorial(n):
"""
Calculate factorial of n
n! = n * (n-1) * (n-2) * ... * 1
"""
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
# Calculation: 5 * 4 * 3 * 2 * 1 = 120
# Trace of factorial(4):
# factorial(4) = 4 * factorial(3)
# factorial(3) = 3 * factorial(2)
# factorial(2) = 2 * factorial(1)
# factorial(1) = 1 # Base case
# Working backwards: 2*1=2, 3*2=6, 4*6=24

6.2 Fibonacci Sequence


# Fibonacci using recursion
def fibonacci(n):
"""
Return nth Fibonacci number
Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
"""
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Print first 10 Fibonacci numbers
for i in range(10):
print(f"F({i}) = {fibonacci(i)}")
# Output:
# F(0) = 0, F(1) = 1, F(2) = 1, F(3) = 2, F(4) = 3
# F(5) = 5, F(6) = 8, F(7) = 13, F(8) = 21, F(9) = 34

6.3 Sum of Digits


# Sum of digits using recursion
def sum_digits(n):
"""Calculate sum of digits of a number"""
# Base case
if n == 0:
return 0
# Recursive case
else:
return (n % 10) + sum_digits(n // 10)
print(sum_digits(12345)) # Output: 15 (1+2+3+4+5)
print(sum_digits(999)) # Output: 27 (9+9+9)

Page 13 of 38
# Trace of sum_digits(123):
# sum_digits(123) = 3 + sum_digits(12)
# sum_digits(12) = 2 + sum_digits(1)
# sum_digits(1) = 1 + sum_digits(0)
# sum_digits(0) = 0 # Base case
# Working backwards: 0, 1+0=1, 2+1=3, 3+3=6

6.4 Recursion vs Iteration


# Power function - Recursive approach
def power_recursive(base, exp):
"""Calculate base^exp using recursion"""
if exp == 0:
return 1
else:
return base * power_recursive(base, exp - 1)
# Power function - Iterative approach
def power_iterative(base, exp):
"""Calculate base^exp using iteration"""
result = 1
for i in range(exp):
result *= base
return result
print(power_recursive(2, 5)) # Output: 32
print(power_iterative(2, 5)) # Output: 32
# When to use recursion:
# - Problem naturally recursive (tree traversal, factorials)
# - Makes code more readable
#
# When to use iteration:
# - Better performance (no function call overhead)
# - Avoids stack overflow for deep recursion

Warning: Deep recursion can cause stack overflow. Python has a default recursion limit
(usually 1000). For large inputs, prefer iterative solutions or increase the limit using
[Link]().

Page 14 of 38
UNIT V
Strings, Lists, Tuples, Dictionaries, and Files

1. Strings and String Methods


Strings are sequences of characters enclosed in quotes. Python provides numerous built-in
methods for string manipulation.

1.1 Creating and Accessing Strings


# Creating strings
str1 = "Hello, World!"
str2 = 'Python Programming'
str3 = """This is a
multi-line
string"""
# Accessing characters (indexing)
text = "Python"
print(text[0]) # Output: P (first character)
print(text[2]) # Output: t
print(text[-1]) # Output: n (last character)
print(text[-2]) # Output: o (second last)
# Slicing [start:stop:step]
print(text[0:3]) # Output: Pyt (characters 0, 1, 2)
print(text[2:]) # Output: thon (from index 2 to end)
print(text[:4]) # Output: Pyth (from start to index 3)
print(text[::2]) # Output: Pto (every 2nd character)
print(text[::-1]) # Output: nohtyP (reverse string)

1.2 String Operations


# Concatenation
first = "Hello"
last = "World"
full = first + " " + last
print(full) # Output: Hello World
# Repetition
dash_line = "-" * 40
print(dash_line) # Output: ----------------------------------------
# Length
text = "Python Programming"
print(len(text)) # Output: 18
# Membership
print("Python" in text) # Output: True
print("Java" in text) # Output: False
print("Java" not in text) # Output: True
# Comparison
print("apple" < "banana") # Output: True (alphabetical)
print("Python" == "python") # Output: False (case-sensitive)

Page 15 of 38
1.3 Important String Methods
text = " Python Programming "
# Case conversion
print([Link]()) # Output: PYTHON PROGRAMMING
print([Link]()) # Output: python programming
print([Link]()) # Output: python programming
print("hello world".title()) # Output: Hello World
# Whitespace removal
print([Link]()) # Output: Python Programming
print([Link]()) # Left strip
print([Link]()) # Right strip
# Finding substrings
sentence = "Python is awesome, Python is powerful"
print([Link]("Python")) # Output: 0 (first occurrence)
print([Link]("Java")) # Output: -1 (not found)
print([Link]("awesome")) # Output: 10
print([Link]("Python")) # Output: 2
# Replacing
new_sentence = [Link]("Python", "Java")
print(new_sentence) # Output: Java is awesome, Java is powerful
# Splitting and joining
words = "apple,banana,orange".split(",")
print(words) # Output: ['apple', 'banana', 'orange']
joined = " - ".join(words)
print(joined) # Output: apple - banana - orange
# Checking string properties
print("hello".isalpha()) # Output: True
print("hello123".isalnum()) # Output: True
print("12345".isdigit()) # Output: True
print(" ".isspace()) # Output: True
print("Hello World".istitle()) # Output: True

1.4 String Formatting


# Old style (% operator)
name = "Alice"
age = 20
print("My name is %s and I am %d years old" % (name, age))
# format() method
print("My name is {} and I am {} years old".format(name, age))
print("My name is {0} and I am {1} years old".format(name, age))
print("My name is {n} and I am {a} years old".format(n=name, a=age))
# f-strings (Python 3.6+) - Recommended
print(f"My name is {name} and I am {age} years old")
# Formatting numbers
pi = 3.14159265
print(f"Pi = {pi:.2f}") # Output: Pi = 3.14
print(f"Pi = {pi:.4f}") # Output: Pi = 3.1416
num = 1234.5678
print(f"{num:,.2f}") # Output: 1,234.57 (with comma)
print(f"{num:10.2f}") # Output: 1234.57 (width 10)
# Expressions in f-strings
x, y = 5, 3
print(f"{x} + {y} = {x + y}") # Output: 5 + 3 = 8

Page 16 of 38
2. Lists
Lists are ordered, mutable (changeable) collections that can hold items of different types.
They are one of the most versatile data structures in Python.

2.1 Creating and Accessing Lists


# Creating lists
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True]
empty_list = []
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: orange (last element)
# Slicing
print(numbers[1:4]) # Output: [2, 3, 4]
print(numbers[:3]) # Output: [1, 2, 3]
print(numbers[2:]) # Output: [3, 4, 5]
print(numbers[::2]) # Output: [1, 3, 5] (every 2nd element)
# Nested lists (2D list/matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0][1]) # Output: 2 (row 0, column 1)
print(matrix[1][2]) # Output: 6 (row 1, column 2)

2.2 List Operations


# Concatenation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5, 6]
# Repetition
repeated = [0] * 5
print(repeated) # Output: [0, 0, 0, 0, 0]
# Length
print(len(combined)) # Output: 6
# Membership
print(3 in list1) # Output: True
print(10 in list1) # Output: False
# Iteration
for item in fruits:
print(item)
# Iteration with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")

2.3 Modifying Lists


numbers = [1, 2, 3, 4, 5]
# Changing elements
numbers[0] = 10
print(numbers) # Output: [10, 2, 3, 4, 5]
# Adding elements
[Link](6) # Add to end
print(numbers) # Output: [10, 2, 3, 4, 5, 6]

Page 17 of 38
[Link](1, 15) # Insert at index 1
print(numbers) # Output: [10, 15, 2, 3, 4, 5, 6]
[Link]([7, 8, 9]) # Add multiple elements
print(numbers) # Output: [10, 15, 2, 3, 4, 5, 6, 7, 8, 9]
# Removing elements
[Link](15) # Remove first occurrence of 15
print(numbers) # Output: [10, 2, 3, 4, 5, 6, 7, 8, 9]
popped = [Link]() # Remove and return last element
print(popped) # Output: 9
print(numbers) # Output: [10, 2, 3, 4, 5, 6, 7, 8]
del numbers[0] # Delete by index
print(numbers) # Output: [2, 3, 4, 5, 6, 7, 8]
[Link]() # Remove all elements
print(numbers) # Output: []

Page 18 of 38
2.4 List Methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
# Sorting
[Link]() # Sort in place (ascending)
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
[Link](reverse=True) # Sort descending
print(numbers) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1]
# Sorted (returns new list)
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original) # Output: [3, 1, 4, 1, 5] (unchanged)
print(sorted_list) # Output: [1, 1, 3, 4, 5]
# Reversing
[Link]()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
# Counting and finding
count = [Link](1)
print(count) # Output: 2
index = [Link](5)
print(index) # Output: 5 (first occurrence)
# Copying
original = [1, 2, 3]
shallow_copy = [Link]() # or original[:]
shallow_copy[0] = 10
print(original) # Output: [1, 2, 3]
print(shallow_copy) # Output: [10, 2, 3]

3. Tuples
Tuples are ordered, immutable (unchangeable) collections. Once created, you cannot modify
their elements. They are faster than lists and protect data from accidental modification.

3.1 Creating and Accessing Tuples


# Creating tuples
coordinates = (10, 20)
fruits = ("apple", "banana", "orange")
mixed = (1, "hello", 3.14, True)
single_element = (5,) # Note the comma
empty_tuple = ()
# Without parentheses (tuple packing)
point = 10, 20, 30
print(type(point)) # Output: <class 'tuple'>
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: orange
# Slicing
print(fruits[0:2]) # Output: ('apple', 'banana')
# Unpacking
x, y = coordinates
print(f"x = {x}, y = {y}") # Output: x = 10, y = 20
# Extended unpacking
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first, middle, last) # Output: 1 [2, 3, 4] 5

3.2 Tuple Operations

Page 19 of 38
# Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
print(combined) # Output: (1, 2, 3, 4, 5, 6)
# Repetition
repeated = (0,) * 5
print(repeated) # Output: (0, 0, 0, 0, 0)
# Length
print(len(combined)) # Output: 6
# Membership
print(3 in tuple1) # Output: True
# Methods
numbers = (1, 2, 3, 2, 4, 2)
print([Link](2)) # Output: 3
print([Link](3)) # Output: 2
# Immutability demonstration
coords = (10, 20)
# coords[0] = 15 # Error: tuples are immutable
# But tuples can contain mutable objects
mixed_tuple = (1, [2, 3], 4)
mixed_tuple[1].append(5) # Can modify the list inside
print(mixed_tuple) # Output: (1, [2, 3, 5], 4)

Page 20 of 38
3.3 When to Use Tuples vs Lists

Aspect Tuples Lists

Mutability Immutable (cannot change) Mutable (can change)

Syntax (1, 2, 3) [1, 2, 3]

Performance Faster Slower

Use Case Fixed data, dict keys Dynamic data

Methods count(), index() Many methods

# Good use of tuples: Returning multiple values


def get_student_info():
name = "Alice"
roll_no = 101
grade = "A"
return name, roll_no, grade # Returns a tuple
student = get_student_info()
print(student) # Output: ('Alice', 101, 'A')
# Good use of tuples: Dictionary keys
locations = {
(0, 0): "Origin",
(1, 2): "Point A",
(3, 4): "Point B"
}
# Lists cannot be dictionary keys (they are mutable)
# locations = {[0, 0]: "Origin"} # Error!

4. Dictionaries
Dictionaries are unordered collections of key-value pairs. They provide fast lookup and are
perfect for storing related information.

4.1 Creating and Accessing Dictionaries


# Creating dictionaries
student = {
"name": "Alice",
"roll_no": 101,
"grade": "A",
"age": 19
}
# Another way to create
student2 = dict(name="Bob", roll_no=102, grade="B")
# Empty dictionary
empty_dict = {}
# Accessing values
print(student["name"]) # Output: Alice
print([Link]("age")) # Output: 19
print([Link]("phone", "Not Available")) # Default value
# Keys can be strings, numbers, or tuples
mixed_dict = {
"name": "Charlie",
1: "one",
(2, 3): "coordinates"

Page 21 of 38
}
# Accessing nested dictionaries
school = {
"students": {
"101": {"name": "Alice", "grade": "A"},
"102": {"name": "Bob", "grade": "B"}
}
}
print(school["students"]["101"]["name"]) # Output: Alice

Page 22 of 38
4.2 Modifying Dictionaries
student = {"name": "Alice", "roll_no": 101}
# Adding new key-value pair
student["grade"] = "A"
student["age"] = 19
print(student) # Output: {'name': 'Alice', 'roll_no': 101, 'grade': 'A', 'age': 19}
# Updating existing value
student["grade"] = "A+"
print(student)
# Updating multiple values
[Link]({"age": 20, "city": "Mumbai"})
print(student)
# Removing items
del student["city"] # Remove specific key
print(student)
removed_value = [Link]("age") # Remove and return value
print(removed_value) # Output: 20
last_item = [Link]() # Remove and return last item
print(last_item)
[Link]() # Remove all items
print(student) # Output: {}

4.3 Dictionary Methods


student = {
"name": "Alice",
"roll_no": 101,
"grade": "A",
"age": 19
}
# Getting keys, values, and items
print([Link]()) # dict_keys(['name', 'roll_no', 'grade', 'age'])
print([Link]()) # dict_values(['Alice', 101, 'A', 19])
print([Link]()) # dict_items([('name', 'Alice'), ...])
# Iterating through dictionary
# Iterate over keys
for key in student:
print(key)
# Iterate over values
for value in [Link]():
print(value)
# Iterate over key-value pairs
for key, value in [Link]():
print(f"{key}: {value}")
# Checking membership
print("name" in student) # Output: True (checks keys)
print("Alice" in [Link]()) # Output: True (checks values)
# Copying
original = {"a": 1, "b": 2}
shallow_copy = [Link]()
shallow_copy["a"] = 10
print(original) # Output: {'a': 1, 'b': 2}
print(shallow_copy) # Output: {'a': 10, 'b': 2}
# setdefault - get value or set default if key doesn't exist
[Link]("city", "Unknown")
print([Link]("city")) # Output: Unknown

Page 23 of 38
4.4 Dictionary Applications
# Word frequency counter
text = "hello world hello python python python"
words = [Link]()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# Output: {'hello': 2, 'world': 1, 'python': 3}
# Student database
students_db = {
101: {"name": "Alice", "marks": [85, 90, 88]},
102: {"name": "Bob", "marks": [78, 82, 80]},
103: {"name": "Charlie", "marks": [92, 95, 89]}
}
# Calculate average marks for each student
for roll_no, info in students_db.items():
avg = sum(info["marks"]) / len(info["marks"])
print(f"{info['name']}: Average = {avg:.2f}")
# Phone book
phonebook = {
"Alice": "123-456-7890",
"Bob": "234-567-8901",
"Charlie": "345-678-9012"
}
name = "Bob"
if name in phonebook:
print(f"{name}'s phone: {phonebook[name]}")

Page 24 of 38
5. List Comprehension
List comprehension provides a concise way to create lists. It's more readable and often faster
than traditional loops.

5.1 Basic List Comprehension


# Traditional way
squares = []
for x in range(1, 6):
[Link](x ** 2)
print(squares) # Output: [1, 4, 9, 16, 25]
# List comprehension way
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
# General syntax: [expression for item in iterable]
# More examples
# Double each number
numbers = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in numbers]
print(doubled) # Output: [2, 4, 6, 8, 10]
# Convert to uppercase
fruits = ["apple", "banana", "orange"]
upper_fruits = [[Link]() for fruit in fruits]
print(upper_fruits) # Output: ['APPLE', 'BANANA', 'ORANGE']
# Create list of tuples
pairs = [(x, x**2) for x in range(1, 6)]
print(pairs) # Output: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

5.2 List Comprehension with Conditions


# Syntax: [expression for item in iterable if condition]
# Even numbers
numbers = range(1, 11)
evens = [x for x in numbers if x % 2 == 0]
print(evens) # Output: [2, 4, 6, 8, 10]
# Squares of even numbers
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(even_squares) # Output: [4, 16, 36, 64, 100]
# Filter and transform
words = ["hello", "world", "python", "programming"]
long_words = [[Link]() for word in words if len(word) > 5]
print(long_words) # Output: ['PYTHON', 'PROGRAMMING']
# Numbers divisible by 3 or 5
divisible = [x for x in range(1, 21) if x % 3 == 0 or x % 5 == 0]
print(divisible) # Output: [3, 5, 6, 9, 10, 12, 15, 18, 20]
# Conditional expression (if-else in comprehension)
# Syntax: [true_expr if condition else false_expr for item in iterable]
result = ["Even" if x % 2 == 0 else "Odd" for x in range(1, 6)]
print(result) # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']

5.3 Nested List Comprehension


# 2D matrix using nested loops
matrix = []
for i in range(3):
row = []
for j in range(3):
[Link](i * 3 + j)
[Link](row)

Page 25 of 38
print(matrix) # Output: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
# Same using list comprehension
matrix = [[i * 3 + j for j in range(3)] for i in range(3)]
print(matrix) # Output: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create multiplication table
mult_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in mult_table:
print(row)
# Transpose a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

5.4 Dictionary and Set Comprehensions


# Dictionary comprehension
# Syntax: {key_expr: value_expr for item in iterable}
# Squares dictionary
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Invert a dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {value: key for key, value in [Link]()}
print(inverted) # Output: {1: 'a', 2: 'b', 3: 'c'}
# Filter dictionary
scores = {"Alice": 85, "Bob": 72, "Charlie": 90, "Diana": 68}
high_scorers = {name: score for name, score in [Link]() if score >= 80}
print(high_scorers) # Output: {'Alice': 85, 'Charlie': 90}
# Set comprehension
# Syntax: {expression for item in iterable}
# Unique squares
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_squares = {x**2 for x in numbers}
print(unique_squares) # Output: {16, 1, 4, 9}
# Unique lengths
words = ["hello", "world", "hi", "python", "code"]
lengths = {len(word) for word in words}
print(lengths) # Output: {2, 4, 5, 6}

Page 26 of 38
6. File Handling
File handling allows programs to read from and write to files, enabling data persistence and
interaction with external data sources.

6.1 Opening and Closing Files


# Opening a file
# Syntax: open(filename, mode)
# Modes: 'r' (read), 'w' (write), 'a' (append), 'r+' (read+write)
# Method 1: Manual closing
file = open("[Link]", "r")
content = [Link]()
[Link]() # Always close files
# Method 2: Using 'with' statement (recommended)
# Automatically closes file
with open("[Link]", "r") as file:
content = [Link]()
# File is automatically closed after this block
# File modes explained:
# 'r' - Read (default). Error if file doesn't exist.
# 'w' - Write. Creates new file or overwrites existing.
# 'a' - Append. Creates new file or adds to existing.
# 'r+' - Read and write. Error if file doesn't exist.
# 'w+' - Write and read. Creates new or overwrites.
# 'a+' - Append and read. Creates new or adds to existing.
# Binary mode (add 'b'): 'rb', 'wb', 'ab'

6.2 Reading Files


# Read entire file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# Read specific number of characters
with open("[Link]", "r") as file:
first_10_chars = [Link](10)
print(first_10_chars)
# Read one line
with open("[Link]", "r") as file:
line = [Link]()
print(line)
# Read all lines into a list
with open("[Link]", "r") as file:
lines = [Link]()
for line in lines:
print([Link]()) # strip() removes newline
# Read line by line (memory efficient for large files)
with open("[Link]", "r") as file:
for line in file:
print([Link]())
# Reading CSV-like data
with open("[Link]", "r") as file:
for line in file:
name, roll_no, grade = [Link]().split(",")
print(f"Name: {name}, Roll: {roll_no}, Grade: {grade}")

6.3 Writing Files


# Write to file (overwrites existing content)
with open("[Link]", "w") as file:

Page 27 of 38
[Link]("Hello, World!\n")
[Link]("This is a new line.\n")
# Write multiple lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("[Link]", "w") as file:
[Link](lines)
# Append to file (adds to existing content)
with open("[Link]", "a") as file:
[Link]("This line is appended.\n")
# Writing data from list
students = [
{"name": "Alice", "roll": 101, "grade": "A"},
{"name": "Bob", "roll": 102, "grade": "B"},
{"name": "Charlie", "roll": 103, "grade": "A+"}
]
with open("[Link]", "w") as file:
for student in students:
line = f"{student['name']},{student['roll']},{student['grade']}\n"
[Link](line)
# Using print() to write to file
with open("[Link]", "w") as file:
print("Hello, World!", file=file)
print("This is printed to file", file=file)

Page 28 of 38
6.4 File Handling Examples
# Example 1: Count words in a file
def count_words(filename):
try:
with open(filename, "r") as file:
content = [Link]()
words = [Link]()
return len(words)
except FileNotFoundError:
return "File not found"
print(f"Word count: {count_words('[Link]')}")
# Example 2: Copy file contents
def copy_file(source, destination):
with open(source, "r") as src:
content = [Link]()
with open(destination, "w") as dest:
[Link](content)
print(f"Copied {source} to {destination}")
copy_file("[Link]", "[Link]")
# Example 3: Read and process data
def calculate_average_marks(filename):
with open(filename, "r") as file:
total = 0
count = 0
for line in file:
name, marks = [Link]().split(",")
total += int(marks)
count += 1
return total / count if count > 0 else 0
# File content: "Alice,85\nBob,90\nCharlie,78"
avg = calculate_average_marks("[Link]")
print(f"Average marks: {avg:.2f}")
# Example 4: Search in file
def search_in_file(filename, search_term):
with open(filename, "r") as file:
for line_num, line in enumerate(file, 1):
if search_term in line:
print(f"Line {line_num}: {[Link]()}")
search_in_file("[Link]", "Python")

7. Exception Handling
Exceptions are errors that occur during program execution. Exception handling allows
programs to deal with errors gracefully without crashing.

7.1 Basic Exception Handling


# Without exception handling
# num = int(input("Enter a number: "))
# This crashes if user enters non-numeric input
# With exception handling
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("Error: Please enter a valid number")
except ZeroDivisionError:
print("Error: Cannot divide by zero")

Page 29 of 38
# Multiple exceptions in one except block
try:
num = int(input("Enter a number: "))
result = 100 / num
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
# Generic exception handler (catches all)
try:
num = int(input("Enter a number: "))
result = 100 / num
except Exception as e:
print(f"An error occurred: {e}")

7.2 try-except-else-finally
# Complete exception handling structure
try:
# Code that might raise an exception
num = int(input("Enter a number: "))
result = 100 / num
except ValueError:
# Handles ValueError
print("Invalid input")
except ZeroDivisionError:
# Handles ZeroDivisionError
print("Cannot divide by zero")
else:
# Executes if no exception occurs
print(f"Result: {result}")
finally:
# Always executes (even if exception occurs)
print("Execution completed")
# File handling with exception
try:
file = open("[Link]", "r")
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
finally:
# Close file if it was opened
try:
[Link]()
print("File closed")
except:
print("File was not opened")
# Better way using 'with'
try:
with open("[Link]", "r") as file:
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found")

Page 30 of 38
7.3 Common Exceptions

Exception Description Example

ValueError Invalid value int("abc")

ZeroDivisionError Division by zero 10 / 0

FileNotFoundError File does not exist open("[Link]")

IndexError Invalid list index list[10]

KeyError Invalid dictionary key dict["key"]

TypeError Invalid type operation "a" + 5

AttributeError Invalid attribute [Link]

ImportError Module not found import missing

7.4 Raising Exceptions


# Raising exceptions manually
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(f"Error: {e}")
# Validating input
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age is unrealistic")
return age
try:
age = set_age(-5)
except ValueError as e:
print(f"Invalid age: {e}")
# Custom exceptions
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Insufficient funds")
return balance - amount
try:
balance = 1000
new_balance = withdraw(balance, 1500)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")

8. Modules and Packages

Page 31 of 38
Modules are Python files containing functions, classes, and variables. Packages are
collections of modules organized in directories.

8.1 Importing Modules


# Method 1: Import entire module
import math
print([Link](16)) # Output: 4.0
print([Link]) # Output: 3.141592653589793
# Method 2: Import specific items
from math import sqrt, pi
print(sqrt(16)) # Output: 4.0
print(pi) # Output: 3.141592653589793
# Method 3: Import with alias
import math as m
print([Link](25)) # Output: 5.0
from math import sqrt as square_root
print(square_root(36)) # Output: 6.0
# Method 4: Import all (not recommended)
from math import *
print(sin(0)) # Output: 0.0
# Multiple imports
import math, random, sys
# Import multiple items
from math import sqrt, pi, sin, cos

Page 32 of 38
8.2 Creating Your Own Modules
# File: [Link] (your module)
"""
Custom math module with utility functions
"""
PI = 3.14159
def add(a, b):
"""Add two numbers"""
return a + b
def multiply(a, b):
"""Multiply two numbers"""
return a * b
def circle_area(radius):
"""Calculate area of circle"""
return PI * radius ** 2
# File: [Link] (using your module)
import mymath
print([Link](5, 3)) # Output: 8
print(mymath.circle_area(5)) # Output: 78.53975
from mymath import add, PI
print(add(10, 20)) # Output: 30
print(PI) # Output: 3.14159

8.3 Common Built-in Modules


# math module
import math
print([Link](4.3)) # Output: 5
print([Link](4.7)) # Output: 4
print([Link](5)) # Output: 120
# random module
import random
print([Link](1, 10)) # Random integer between 1 and 10
print([Link]([1, 2, 3])) # Random choice from list
print([Link]()) # Random float between 0 and 1
numbers = [1, 2, 3, 4, 5]
[Link](numbers) # Shuffle list in place
print(numbers)
# datetime module
from datetime import datetime, date
now = [Link]()
print(now) # Current date and time
print([Link], [Link], [Link])
today = [Link]()
print(today) # Current date
# os module (operating system interface)
import os
print([Link]()) # Current working directory
# [Link]("new_folder") # Create directory
# [Link](".") # List files in directory
# sys module (system-specific parameters)
import sys
print([Link]) # Python version
print([Link]) # Operating system

8.4 Packages

Page 33 of 38
A package is a directory containing multiple modules and a special __init__.py file. It helps
organize related modules.

# Package structure:
# mypackage/
# __init__.py
# [Link]
# [Link]
# subpackage/
# __init__.py
# [Link]
# File: mypackage/[Link]
def func1():
return "Function from module1"
# File: mypackage/[Link]
def func2():
return "Function from module2"
# File: mypackage/__init__.py
# Can be empty or contain initialization code
# Using the package:
# Method 1
import mypackage.module1
print(mypackage.module1.func1())
# Method 2
from mypackage import module1, module2
print(module1.func1())
print(module2.func2())
# Method 3
from mypackage.module1 import func1
print(func1())

8.5 The __name__ Variable


# File: [Link]
def my_function():
print("Function in mymodule")
print(f"__name__ in mymodule: {__name__}")
if __name__ == "__main__":
# This code runs only when file is executed directly
# Not when imported as a module
print("mymodule is being run directly")
my_function()
# When you run [Link]:
# __name__ in mymodule: __main__
# mymodule is being run directly
# Function in mymodule
# When you import mymodule:
# __name__ in mymodule: mymodule
# Practical use - testing module
if __name__ == "__main__":
# Test code here
print("Running tests...")
assert add(2, 3) == 5
print("All tests passed!")

Page 34 of 38
Practice Problems

Unit IV Practice Problems


1. Write a program that takes a number as input and prints whether it's
positive, negative, or zero using proper indentation.
2. Create a function that calculates the factorial of a number using both
iteration and recursion. Compare the results.
3. Write a program that takes two numbers and an operator (+, -, *, /) as
input and performs the calculation using functions.
4. Create a recursive function to calculate the nth Fibonacci number and
print the first 15 Fibonacci numbers.
5. Write a function that takes a string as input and returns the number of
vowels in it.
6. Create a calculator program that continues to ask for operations until
the user types 'quit'.
7. Write a program that demonstrates the difference between global and local
variables.
8. Create a function that takes variable number of arguments and returns
their sum and average.
9. Write a recursive function to reverse a string.
10. Create a program that demonstrates the use of lambda functions with
map(), filter(), and sorted().

Unit V Practice Problems


1. Write a program that takes a sentence as input and prints each word on
a new line, along with its length.
2. Create a program that reads a file containing student names and marks,
and calculates the average marks.
3. Write a program that creates a dictionary of words and their frequencies
from a given text.
4. Create a list of 20 random numbers and use list comprehension to:
- Find all even numbers
- Square all odd numbers
- Create pairs (number, square)
5. Write a program that reads a file, counts the number of lines, words,
and characters, and writes the statistics to another file.
6. Create a program that maintains a student database using dictionaries:
- Add new students
- Update marks
- Display all students
- Calculate class average
7. Write a program that handles multiple types of exceptions when:
- Reading a file
- Converting user input to integer
- Accessing list elements
8. Create a module with functions for basic geometry (area and perimeter

Page 35 of 38
of circle, rectangle, triangle) and use it in another program.
9. Write a program using list comprehension to create a multiplication
table (1-10) as a 2D list.
10. Create a program that:
- Reads student data from a file
- Processes it using dictionaries
- Handles file not found and invalid data exceptions
- Writes results to another file

Page 36 of 38
Summary and Learning Tips

Key Takeaways - Unit IV


• Python uses indentation (4 spaces) to define code blocks
• Keywords are reserved words with special meanings
• Identifiers must follow naming rules and conventions
• Functions help organize code and avoid repetition
• Recursion requires a base case and recursive case
• input() always returns a string - convert as needed
• Use f-strings for modern string formatting
• Practice is essential - write code every day!

Key Takeaways - Unit V


• Strings are immutable - methods return new strings
• Lists are mutable and versatile
• Tuples are immutable and faster than lists
• Dictionaries provide fast key-value storage
• List comprehensions are concise and Pythonic
• Always use 'with' statement for file handling
• Handle exceptions to make programs robust
• Organize code into modules and packages
• Use appropriate data structure for the task
• Read documentation and explore built-in modules

Study Tips for Success

Tip Description

Practice Daily Write code every day, even for 30 minutes

Type, Don't Copy Type code examples to build muscle memory

Break Down Problems Divide complex problems into smaller parts

Use Print Statements Debug by printing values at each step

Read Error Messages Errors tell you exactly what's wrong

Experiment Try variations of examples to understand

Build Projects Apply concepts in mini-projects

Use Python Tutor Visualize code execution online

Join Communities Ask questions on forums and groups

Page 37 of 38
Review Regularly Revisit concepts weekly for retention

Additional Resources
Official Documentation: [Link] Interactive Learning: [Link], [Link]
Practice Platforms: HackerRank, LeetCode, Codewars Video Tutorials: YouTube channels
(Corey Schafer, Programming with Mosh) Books: "Python Crash Course" by Eric Matthes,
"Automate the Boring Stuff" Remember: Programming is a skill that improves with practice.
Don't get discouraged by errors - they're part of the learning process. Every expert
programmer was once a beginner! Good luck with your Python programming journey! ■

Page 38 of 38

You might also like