Module IV: Python Programming Ref: Reema Thareja
MODULE IV
Python Programming – Study Notes
Reference: Python Programming Using Problem Solving Approach by Reema Thareja
SECTION 1: DICTIONARIES
1.1 Introduction to Dictionaries
A dictionary in Python is an unordered collection of key-value pairs. Each key-value pair maps a key to
its associated value. Dictionaries are mutable, meaning their content can be changed after creation. They
are also known as associative arrays or hash maps in other programming languages.
Dictionaries are enclosed in curly braces {} and each key-value pair is separated by a colon (:). Multiple
pairs are separated by commas.
1.2 Creating a Dictionary
There are several ways to create a dictionary in Python:
Method 1: Using Curly Braces
# Empty dictionary
my_dict = {}
# Dictionary with initial values
student = {'name': 'Alice', 'age': 20, 'marks': 85}
print(student)
Output:
{'name': 'Alice', 'age': 20, 'marks': 85}
Method 2: Using the dict() Constructor
student = dict(name='Bob', age=21, marks=90)
print(student)
# From a list of tuples
pairs = [('a', 1), ('b', 2), ('c', 3)]
d = dict(pairs)
print(d)
Output:
{'name': 'Bob', 'age': 21, 'marks': 90}
{'a': 1, 'b': 2, 'c': 3}
1.3 Accessing Values in a Dictionary
Dictionary values are accessed using their keys inside square brackets [ ] or via the get() method.
student = {'name': 'Alice', 'age': 20, 'marks': 85}
Python Programming | Module IV Study Notes 1
Module IV: Python Programming Ref: Reema Thareja
# Using square brackets
print(student['name'])
# Using get() - safer, returns None if key not found
print([Link]('age'))
print([Link]('grade', 'N/A')) # default value
Output:
Alice
20
N/A
1.4 Modifying a Dictionary (Operations)
Adding and Updating Elements
student = {'name': 'Alice', 'age': 20}
student['marks'] = 85 # Adding a new key-value pair
student['age'] = 21 # Updating an existing value
print(student)
Output:
{'name': 'Alice', 'age': 21, 'marks': 85}
Deleting Elements
student = {'name': 'Alice', 'age': 20, 'marks': 85}
del student['marks'] # Removes 'marks'
print(student)
val = [Link]('age') # Removes 'age', returns value
print('Popped value:', val)
print(student)
Output:
{'name': 'Alice', 'age': 20}
Popped value: 20
{'name': 'Alice'}
1.5 Built-in Dictionary Functions and Methods
Method / Function Description & Example
len(d) Returns the number of key-value pairs. len({'a':1, 'b':2}) → 2
str(d) Converts the dictionary to a string representation. str({'a':1}) →
"{'a': 1}"
[Link]() Returns a view of all keys in the dictionary.
{'name':'Alice','age':20}.keys() → dict_keys(['name','age'])
[Link]() Returns a view of all values. {'name':'Alice','age':20}.values() →
dict_values(['Alice',20])
Python Programming | Module IV Study Notes 2
Module IV: Python Programming Ref: Reema Thareja
[Link]() Returns all key-value pairs as a view of tuples. {'a':1}.items() →
dict_items([('a',1)])
[Link](k, def) Returns value of key k, or default if key not found.
[Link]('grade','N/A') → 'N/A'
[Link](d2) Merges dictionary d2 into d, updating existing keys.
[Link](key) Removes and returns the value of the given key.
[Link]() Removes and returns the last inserted (key, value) pair.
[Link](k,v) Returns value if key exists; otherwise inserts key with value v.
[Link]() Returns a shallow copy of the dictionary. d2 = [Link]()
[Link]() Removes all key-value pairs from the dictionary. [Link]() → {}
key in d Returns True if key exists in the dictionary. 'name' in student →
True
Comprehensive Demo – All Dictionary Methods
# ── Dictionary Methods Demonstration ──────────────────
student = {'name': 'Alice', 'age': 20, 'marks': 85}
# len() – number of key-value pairs
print('len() :', len(student))
# str() – string representation
print('str() :', str(student))
# keys() – all keys
print('keys() :', [Link]())
# values() – all values
print('values() :', [Link]())
# items() – all key-value pairs
print('items() :', [Link]())
# get() – safe access
print('get(marks) :', [Link]('marks'))
print('get(grade) :', [Link]('grade', 'N/A'))
# update() – merge another dict
[Link]({'grade': 'A', 'city': 'Delhi'})
print('update() :', student)
# setdefault() – insert if missing
[Link]('country', 'India')
print('setdefault():', student)
# copy() – shallow copy
copy_dict = [Link]()
print('copy() :', copy_dict)
# popitem() – remove last inserted pair
removed = [Link]()
Python Programming | Module IV Study Notes 3
Module IV: Python Programming Ref: Reema Thareja
print('popitem() :', removed)
print('After popitem:', student)
# pop() – remove specific key
val = [Link]('city')
print('pop(city) :', val)
print('After pop :', student)
# 'in' operator – key membership
print('name in dict:', 'name' in student)
print('score in dict:', 'score' in student)
# clear() – remove everything
[Link]()
print('clear() :', student)
Output:
len() : 3
str() : {'name': 'Alice', 'age': 20, 'marks': 85}
keys() : dict_keys(['name', 'age', 'marks'])
values() : dict_values(['Alice', 20, 85])
items() : dict_items([('name', 'Alice'), ('age', 20), ('marks', 85)])
get(marks) : 85
get(grade) : N/A
update() : {'name': 'Alice', 'age': 20, 'marks': 85, 'grade': 'A', 'city':
'Delhi'}
setdefault(): {'name': 'Alice', 'age': 20, 'marks': 85, 'grade': 'A', 'city':
'Delhi', 'country': 'India'}
copy() : {'name': 'Alice', 'age': 20, 'marks': 85, 'grade': 'A', 'city':
'Delhi', 'country': 'India'}
popitem() : ('country', 'India')
After popitem: {'name': 'Alice', 'age': 20, 'marks': 85, 'grade': 'A', 'city':
'Delhi'}
pop(city) : Delhi
After pop : {'name': 'Alice', 'age': 20, 'marks': 85, 'grade': 'A'}
name in dict: True
score in dict: False
clear() : {}
1.6 Looping Over a Dictionary
student = {'name': 'Alice', 'age': 20, 'marks': 85}
# Loop over keys (default)
print('--- Keys ---')
for key in student:
print(key)
# Loop over values
print('--- Values ---')
for val in [Link]():
print(val)
# Loop over key-value pairs
print('--- Items ---')
for key, val in [Link]():
print(f'{key}: {val}')
Python Programming | Module IV Study Notes 4
Module IV: Python Programming Ref: Reema Thareja
Output:
--- Keys ---
name
age
marks
--- Values ---
Alice
20
85
--- Items ---
name: Alice
age: 20
marks: 85
1.7 Nested Dictionaries
school = {
'student1': {'name': 'Alice', 'age': 20, 'marks': 85},
'student2': {'name': 'Bob', 'age': 21, 'marks': 90},
}
# Accessing nested values
print(school['student1']['name'])
print(school['student2']['marks'])
# Modifying a nested value
school['student1']['marks'] = 92
print(school['student1'])
Output:
Alice
90
{'name': 'Alice', 'age': 20, 'marks': 92}
1.8 List vs Tuples vs Dictionaries vs Sets
Feature List Tuple Dictionary Set
Ordered Yes Yes Yes (Py 3.7+) No
Mutable Yes No Yes Yes
Duplicates Yes Yes Keys: No No
Syntax [] () { key:val } {}
Access by Index Index Key N/A
Use case General seq. Fixed data Key-value Unique items
Python Programming | Module IV Study Notes 5
Module IV: Python Programming Ref: Reema Thareja
SECTION 2: STRINGS
2.1 Introduction to Strings
A string in Python is a sequence of characters enclosed in single quotes (' '), double quotes (" "), or triple
quotes (''' ''' or """ """). Strings are immutable in Python, meaning their contents cannot be changed after
creation.
s1 = 'Hello, World!'
s2 = "Python Programming"
s3 = '''This is a
multi-line string'''
print(s1)
print(type(s1))
Output:
Hello, World!
<class 'str'>
2.2 Formatting Operator (%)
The % operator (also called the string formatting or interpolation operator) is used to format strings by
embedding values into a string template.
name = 'Alice'
age = 20
marks = 85.5
print('Name: %s' % name)
print('Age: %d, Marks: %.1f' % (age, marks))
print('Hex of 255: %x' % 255)
print('Octal of 8: %o' % 8)
Output:
Name: Alice
Age: 20, Marks: 85.5
Hex of 255: ff
Octal of 8: 10
Format Specifiers: %s – string %d – integer %f – float %e – scientific %o – octal %x
– hexadecimal
2.3 String Operations
Concatenation & Repetition
a = 'Hello'
b = ' World'
print(a + b) # concatenation
print(a * 3) # repetition
Output:
Hello World
HelloHelloHello
Python Programming | Module IV Study Notes 6
Module IV: Python Programming Ref: Reema Thareja
Slicing & Indexing
s = 'Python'
print(s[0]) # positive index
print(s[-1]) # negative index
print(s[0:3]) # slice: start:stop
print(s[::2]) # step slicing
print(s[::-1]) # reverse
Output:
P
n
Pyt
Pto
nohtyP
Membership & Comparison
print('Py' in 'Python')
print('py' not in 'Python')
print('abc' == 'abc')
print('apple' < 'mango')
Output:
True
True
True
True
2.4 Built-in String Methods and Functions
Method Description & Example
upper() Converts to uppercase. 'hello'.upper() → 'HELLO'
lower() Converts to lowercase. 'HELLO'.lower() → 'hello'
capitalize() Capitalises only the first character. 'hello world'.capitalize() →
'Hello world'
title() Capitalises first letter of each word. 'hello world'.title() → 'Hello
World'
strip() Removes leading and trailing whitespace. ' hi '.strip() → 'hi'
lstrip() / rstrip() Removes left or right whitespace only.
replace(old, new) Replaces all occurrences of old with new. 'hello'.replace('l','r') →
'herro'
split(sep) Splits string into a list at separator. 'a,b,c'.split(',') → ['a','b','c']
join(iterable) Joins list elements with the string as separator. ','.join(['a','b','c'])
→ 'a,b,c'
find(sub) Returns index of first occurrence; -1 if not found. 'hello'.find('ll') →
2
index(sub) Like find() but raises ValueError if not found.
Python Programming | Module IV Study Notes 7
Module IV: Python Programming Ref: Reema Thareja
count(sub) Counts non-overlapping occurrences. 'banana'.count('a') → 3
startswith(prefix) Returns True if string starts with prefix. 'Python'.startswith('Py') →
True
endswith(suffix) Returns True if string ends with suffix. 'Python'.endswith('on') →
True
isdigit() Returns True if all characters are digits. '123'.isdigit() → True
isalpha() Returns True if all characters are alphabets. 'abc'.isalpha() →
True
isalnum() Returns True if all characters are alphanumeric.
'abc123'.isalnum() → True
len(s) Returns the number of characters. len('hello') → 5
sorted(s) Returns a sorted list of characters. sorted('bca') → ['a','b','c']
Demo – Common String Methods
s = ' Hello, Python World! '
print('Original :', repr(s))
print('upper() :', [Link]())
print('lower() :', [Link]())
print('strip() :', [Link]())
print('replace():', [Link]().replace('Python', 'Amazing'))
print('split() :', [Link]().split())
print('find() :', [Link]('Python'))
print('count() :', [Link]('l'))
print('starts() :', [Link]().startswith('Hello'))
print('ends() :', [Link]().endswith('!'))
print('len() :', len([Link]()))
words = ['Python', 'is', 'fun']
print('join() :', ' '.join(words))
Output:
Original : ' Hello, Python World! '
upper() : HELLO, PYTHON WORLD!
lower() : hello, python world!
strip() : Hello, Python World!
replace(): Hello, Amazing World!
split() : ['Hello,', 'Python', 'World!']
find() : 9
count() : 3
starts() : True
ends() : True
len() : 21
join() : Python is fun
2.5 Iterating a String
s = 'Python'
# Character by character
Python Programming | Module IV Study Notes 8
Module IV: Python Programming Ref: Reema Thareja
for ch in s:
print(ch, end=' ')
print() # newline
# Using enumerate for index + character
for i, ch in enumerate(s):
print(f'Index {i}: {ch}')
Output:
P y t h o n
Index 0: P
Index 1: y
Index 2: t
Index 3: h
Index 4: o
Index 5: n
2.6 String Module
import string
print('ascii_lowercase:', string.ascii_lowercase)
print('ascii_uppercase:', string.ascii_uppercase)
print('digits :', [Link])
print('punctuation :', [Link])
Output:
ascii_lowercase: abcdefghijklmnopqrstuvwxyz
ascii_uppercase: ABCDEFGHIJKLMNOPQRSTUVWXYZ
digits : 0123456789
punctuation : !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
2.7 Comparing Strings
print('apple' == 'apple')
print('apple' != 'mango')
print('apple' < 'mango') # 'a' < 'm' in ASCII
print('Banana' < 'apple') # 'B'(66) < 'a'(97)
# Case-insensitive comparison
print('Apple'.lower() == 'apple'.lower())
Output:
True
True
True
True
True
2.8 Regular Expressions
Regular expressions (regex) are patterns used to match, search, and manipulate strings. Python provides
the re module for this purpose.
Common re Functions
Python Programming | Module IV Study Notes 9
Module IV: Python Programming Ref: Reema Thareja
Function Description
[Link](pat, str) Matches pattern at the beginning of string; returns match object
or None
[Link](pat, str) Searches for pattern anywhere in string; returns first match or
None
[Link](pat, str) Returns a list of all non-overlapping matches
[Link](pat, str) Returns an iterator of all match objects
[Link](pat, repl, str) Replaces all matches of pattern with repl and returns new string
[Link](pat, str) Splits the string at each occurrence of the pattern
[Link](pat) Compiles a pattern into a regex object for repeated use
Common Regex Patterns
Pattern Meaning
. Any single character except newline
^ Matches the start of the string
$ Matches the end of the string
* 0 or more repetitions of preceding element
+ 1 or more repetitions of preceding element
? 0 or 1 repetition (makes preceding element optional)
\d Any digit [0-9]
\D Any non-digit character
\w Any word character [a-zA-Z0-9_]
\W Any non-word character
\s Any whitespace character (space, tab, newline)
[abc] Any one of a, b, or c
[^abc] Any character except a, b, or c
{n,m} Between n and m repetitions of preceding element
Regex Examples
import re
text = 'My phone is 9876543210 and email is user@[Link]'
# 1. findall – extract 10-digit phone number
phone = [Link](r'\d{10}', text)
print('Phone:', phone)
Python Programming | Module IV Study Notes 10
Module IV: Python Programming Ref: Reema Thareja
# 2. search – find an email address
match = [Link](r'[\w.-]+@[\w.-]+\.\w+', text)
if match:
print('Email:', [Link]())
# 3. sub – mask all digits with *
masked = [Link](r'\d', '*', text)
print('Masked:', masked)
# 4. match – check if string starts with 'My'
m = [Link](r'My', text)
print('Starts with My:', bool(m))
# 5. split – split on spaces or punctuation
words = [Link](r'\s+', text)
print('Words:', words[:4], '...')
Output:
Phone: ['9876543210']
Email: user@[Link]
Masked: My phone is ********** and email is user@[Link]
Starts with My: True
Words: ['My', 'phone', 'is', '9876543210'] ...
Python Programming | Module IV Study Notes 11
Module IV: Python Programming Ref: Reema Thareja
SECTION 3: FILE HANDLING
3.1 Introduction to File Handling
File handling allows Python programs to work with files stored on the disk — reading data from them or
writing data to them. This is essential for data persistence, since data in variables is lost when the
program ends.
Why File Handling? Variables store data in RAM (temporary). Files store data on disk
(permanent). File handling bridges this gap.
3.2 File Paths
A file path specifies the location of a file on the file system.
Types of Paths
• Absolute Path: Full path from the root directory.
# Windows: C:\Users\Alice\Documents\[Link]
# Linux/Mac: /home/alice/documents/[Link]
• Relative Path: Path relative to the current working directory.
# If current dir is C:\Users\Alice\:
# 'Documents\[Link]' refers to the same absolute path above
The [Link] Module
import os
print([Link]())
print([Link]('[Link]'))
print([Link]('[Link]'))
print([Link]('documents', '[Link]'))
Output:
C:\Users\Alice\Desktop
C:\Users\Alice\Desktop\[Link]
True
documents\[Link]
3.3 Types of Files
File Type Description Example Extensions
Text File Stores data as human-readable .txt, .csv, .py,
characters (ASCII/Unicode). .html, .json
Can be opened with any text
editor.
Binary File Stores data in machine- .jpg, .png, .mp3,
readable binary format (0s and .exe, .pdf
1s). Requires specific
programs to open.
Python Programming | Module IV Study Notes 12
Module IV: Python Programming Ref: Reema Thareja
3.4 Opening and Closing Files
Files must be opened before they can be read or written. The open() function returns a file object.
file_object = open(filename, mode)
File Opening Modes
Mode Description
'r' Read (default). File must exist. File pointer placed at the beginning.
'w' Write. Creates file if it does not exist; overwrites if it does.
'a' Append. Creates file if not exists; adds content to end if it exists.
'r+' Read and Write. File must already exist.
'w+' Write and Read. Truncates file or creates a new one.
'a+' Append and Read.
'rb' Read in binary mode.
'wb' Write in binary mode.
Opening and Closing – Example
# Method 1: Manual open and close
f = open('[Link]', 'w')
[Link]('Hello, World!')
[Link]() # Always close the file
print('File closed:', [Link])
# Method 2: 'with' statement (recommended – auto closes)
with open('[Link]', 'r') as f:
content = [Link]()
print('Content:', content)
print('Auto closed:', [Link])
Output:
File closed: True
Content: Hello, World!
Auto closed: True
3.5 Reading and Writing Files
Reading Methods
Method Description
[Link]() Reads the entire file and returns it as a single string.
[Link](n) Reads exactly n characters from the current file position.
[Link]() Reads one line at a time (including the newline character \n).
[Link]() Reads all lines and returns them as a list of strings.
Python Programming | Module IV Study Notes 13
Module IV: Python Programming Ref: Reema Thareja
Reading Examples
# Assume '[Link]' contains:
# Line 1: Python is easy
# Line 2: File handling is useful
# Line 3: Practice makes perfect
# read() – entire file
with open('[Link]', 'r') as f:
print([Link]())
# readline() – one line
with open('[Link]', 'r') as f:
print([Link]())
# readlines() – all lines as list
with open('[Link]', 'r') as f:
print([Link]())
# Iterating line by line
with open('[Link]', 'r') as f:
for line in f:
print([Link]())
Output:
Python is easy
File handling is useful
Practice makes perfect
Python is easy
['Python is easy\n', 'File handling is useful\n', 'Practice makes perfect']
Python is easy
File handling is useful
Practice makes perfect
Writing Methods
Method Description
[Link](str) Writes a string to the file. Returns number of characters written.
Does NOT add newline automatically.
[Link](list) Writes a list of strings to the file. Does NOT add newlines
automatically; include \n in each string.
Writing Examples
# write() – create and write
with open('[Link]', 'w') as f:
n = [Link]('Hello, World!\n')
print('Characters written:', n)
[Link]('Python is great!\n')
# append() – add to existing
with open('[Link]', 'a') as f:
[Link]('One more line.\n')
Python Programming | Module IV Study Notes 14
Module IV: Python Programming Ref: Reema Thareja
# writelines() – write multiple lines
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('[Link]', 'w') as f:
[Link](lines)
# Verify contents
with open('[Link]', 'r') as f:
print([Link]())
Output:
Characters written: 14
Line 1
Line 2
Line 3
File Pointer: seek() and tell()
with open('[Link]', 'w') as f:
[Link]('Python Programming')
with open('[Link]', 'r') as f:
print('Position:', [Link]()) # start
[Link](6) # read 6 chars
print('Position:', [Link]()) # after read
[Link](0) # go back to start
print('First 3 chars:', [Link](3))
Output:
Position: 0
Position: 6
First 3 chars: Pyt
3.6 Directory Methods
The os module provides functions to work with directories (folders) on the file system.
Method Description
[Link]() Returns a string with the current working directory path.
[Link](path) Changes the current working directory to the given path.
[Link](path) Returns a list of all files and folders in the given directory.
[Link](path) Creates a single new directory at the specified path.
[Link](path) Creates a directory and all necessary parent directories
(recursive).
[Link](path) Removes an empty directory.
[Link](path) Removes directories recursively (all must be empty).
[Link](old, new) Renames a file or directory from old name to new name.
[Link](path) Permanently deletes a file from the file system.
[Link](path) Returns True if the given path exists, False otherwise.
Python Programming | Module IV Study Notes 15
Module IV: Python Programming Ref: Reema Thareja
[Link](path) Returns True if the path points to a file.
[Link](path) Returns True if the path points to a directory.
Comprehensive Demo – Directory Methods
import os
# 1. getcwd() – current directory
print('CWD:', [Link]())
# 2. mkdir() – create a folder
[Link]('test_folder')
print('mkdir done')
# 3. makedirs() – create nested folders
[Link]('parent/child/grandchild')
print('makedirs done')
# 4. listdir() – contents of current directory
print('listdir:', [Link]('.'))
# 5. [Link]() / isdir() / isfile()
print('Exists? :', [Link]('test_folder'))
print('Is dir? :', [Link]('test_folder'))
print('Is file? :', [Link]('test_folder'))
# 6. rename() – rename a file
with open('[Link]', 'w') as f:
[Link]('test')
[Link]('[Link]', '[Link]')
print('After rename:', [Link]('.'))
# 7. chdir() – change directory
[Link]('test_folder')
print('Changed to:', [Link]())
[Link]('..') # go back up
# 8. remove() – delete a file
[Link]('[Link]')
print('File removed')
# 9. rmdir() – remove empty folder
[Link]('test_folder')
print('Folder removed')
Output:
CWD: C:\Users\Alice\Desktop
mkdir done
makedirs done
listdir: ['test_folder', 'parent', '[Link]', '[Link]', '[Link]']
Exists? : True
Is dir? : True
Is file? : False
After rename: ['test_folder', 'parent', '[Link]', '[Link]', '[Link]']
Changed to: C:\Users\Alice\Desktop\test_folder
File removed
Folder removed
Python Programming | Module IV Study Notes 16
Module IV: Python Programming Ref: Reema Thareja
Python Programming | Module IV Study Notes 17
Module IV: Python Programming Ref: Reema Thareja
MODULE IV – QUICK REFERENCE SUMMARY
Topic Key Points
Dictionary Mutable, key-value pairs, ordered (Py 3.7+). Created with {}. Access via
key or get(). Methods: keys(), values(), items(), update(), pop(), copy(),
clear(), len(), str()
Nested Dict A dict inside another dict. Access with multiple [ ] operators:
d['key1']['key2']
Strings Immutable sequence of characters. Supports slicing, concatenation (* , +),
and many built-in methods
% Operator String formatting: 'Hello %s' % name. Specifiers: %s %d %f %e %o %x
String Methods upper(), lower(), strip(), split(), join(), replace(), find(), count(), startswith(),
endswith()
String Module import string. Constants: ascii_letters, digits, punctuation, whitespace
Regex (re) import re. Functions: match(), search(), findall(), sub(), split(). Patterns: \d
\w \s . ^ $ * + ?
File Modes 'r' read, 'w' write (overwrite), 'a' append, 'r+' read+write, 'b' binary mode
Read Methods read(), read(n), readline(), readlines()
Write Methods write(str), writelines(list)
with statement Best practice for files: auto-closes file even if exception occurs
OS / Directory [Link](), chdir(), listdir(), mkdir(), makedirs(), rename(), remove(),
rmdir()
End of Module IV Study Notes
Python Programming | Module IV Study Notes 18