Module 3 Notes
Module 3 Notes
MODULE 3
INTRODUCTION TO PYTHON PROGRAMMING
Syllabus: Manipulating Strings: Working with Strings, Useful String Methods, Project: Password Locker,
Project: Adding Bullets to Wiki Markup Reading and Writing Files: Files and File Paths, The os.path
Module, The File Reading/Writing Process, Saving Variables with the shelve Module,Saving Variables
with the print.format() Function, Project: Generating Random Quiz Files, Project: Multi Clipboard,
Textbook 1: Chapters 6 , 8
E
DEFINITION: In programming, a string is a sequence of characters enclosed in quotation marks. These
C
characters can be letters, numbers, symbols, or whitespace.
N
JN
Types of Strings:
L,
○ Example: 'Hello'
IM
2. Double-quoted strings:
○ Created using double quotes (" ")
○ Example: "World"
,A
3. Raw strings:
○ Created by prefixing the string with r or R (e.g., r'...' or R'...').
M
○ These strings treat backslashes as literal characters and not escape characters.
○ Example: r'C:\Users\Al'
EE
Example:
W
'''This is a
multiline string.'''
YA
String Example:
LI
Strings are widely used for text processing, storing data, and more in programming.
Python provides several ways to create, manipulate, and display strings. Let’s break it down step by step:
String Literals:A string in Python is a sequence of characters enclosed in quotes. There are two types of
string quotes:
Aaliya Waseem,Dept.AIML,JNNCE
1
Introduction to python programming BPLCK105B
Using Double Quotes for Strings: If you want to include a single quote inside a string, you can use
double quotes:
spam = "That's Alice's cat."
In this case, the double quotes tell Python where the string starts and ends, and the single quote inside the
string is not considered as the end of the string.
E
C
Escape Characters: Sometimes, you need special characters inside a string, such as quotes, backslashes,
or new lines. This is where escape characters come in.
N
JN
What is an Escape Character?
An escape character is a backslash (\) followed by a character that modifies the string. Even though it
consists of two characters, it is considered a single escape character.
L,
IM
,A
M
EE
AS
W
Aaliya Waseem,Dept.AIML,JNNCE
2
Introduction to python programming BPLCK105B
path = 'C:\\Users\\Alice'
# New line
poem = 'Roses are red,\nViolets are blue.'
# Tab
tabbed_text = 'Name\tAge\tLocation'
Conclusion
E
● Escape Characters: Allow special characters like quotes, backslashes, and new lines inside
C
strings.
N
This makes it easy to include complex text in Python strings without errors.
JN
2. RAW STRINGS MULTILINE STRINGS
Raw Strings: A raw string is a string where Python ignores all escape characters. This means that
L,
backslashes are treated as part of the string, not as escape characters.
IM
Why use raw strings? When working with strings that contain many backslashes, such as file paths or
regular expressions.
,A
Example of a Raw String:
M
print(r'C:\Users\Al\Desktop')
EE
Output: C:\Users\Al\Desktop
AS
In this case, the \n, \t, and \ characters are treated as part of the string rather than special escape characters.
Multiline Strings: Sometimes you need a string that spans multiple lines. Instead of using multiple \n
W
● Begins and ends with three single quotes ''' or three double quotes """.
● All lines within the triple quotes are considered part of the string.
LI
print('''Hello,
This is a multiline string example.
You can include newlines, single quotes, and double quotes.''')
Output:
Hello,
This is a multiline string example.
You can include newlines, single quotes, and double quotes.
Aaliya Waseem,Dept.AIML,JNNCE
3
Introduction to python programming BPLCK105B
You can also escape quotes inside multiline strings, but it’s optional:
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
Output:
Dear Alice,
E
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
C
Sincerely,
Bob
N
JN
Using Triple Quotes for Comments: Multiline strings can also be used for comments that span multiple
lines.
Example:
L,
IM
# Regular comment
print('Hello!') # This is a single-line comment
,A
# Multiline comment using triple quotes
""This is a test Python program.
M
This is useful when you need to write long explanations or document a program in a more detailed way””
EE
Each character in the string has a position number called an index. These start at 0 for the first
character, then go 1, 2, 3, and so on.
YA
Here’s how the string "Hello, world!" looks with its index numbers:
LI
AA
If you want to grab just one character, you can use its index like this:
Aaliya Waseem,Dept.AIML,JNNCE
4
Introduction to python programming BPLCK105B
E
C
You can also take parts of the string by slicing it. To slice, you give a starting index and an ending
index like this:
N
print(spam[0:5]) # Gets characters from position 0 to 4: 'Hello'
JN
● The starting index is included.
● The ending index is not included.
L,
So spam[0:5] means:
IM
Start at position 0 (H), go up to (but not include) position 5.
,A
Shortcuts for Slicing
M
If you don’t give a starting or ending index, Python assumes some defaults:
EE
When you slice a string, Python gives you a copy of the part you asked for. The original string doesn’t
change:
LI
fizz = spam[0:5]
print(fizz) # 'Hello' (just the part you sliced)
print(spam) # 'Hello, world!' (the original string is still the same)
Key Points:
1. Strings are like lists of characters, and you can use numbers (indexes) to pick parts of them.
2. Indexes start at 0 for the first character.
3. Slicing lets you pick parts of the string, from one position to another.
Aaliya Waseem,Dept.AIML,JNNCE
5
Introduction to python programming BPLCK105B
4. The original string doesn’t change when you slice it.
The in and not in operators let you check if one string is inside another string. These checks give you a
simple True or False answer.
The in Operator
E
The in operator checks if a smaller string (a substring) is inside a bigger string.
C
If the smaller string is found, the result is True. If it’s not found, the result is False.
N
Examples:
JN
print('Hello' in 'Hello, World') # True, because 'Hello' is inside 'Hello, World'
L,
print('HELLO' in 'Hello, World') # False, because Python is case-sensitive ('HELLO' ≠ 'Hello')
IM
print('' in 'spam') # True, because an empty string is technically everywhere
Examples:
EE
print('cats' not in 'cats and dogs') # False, because 'cats' *is* inside 'cats and dogs'
AS
print('fish' not in 'cats and dogs') # True, because 'fish' is not in 'cats and dogs'
1. Case matters: 'Hello' and 'HELLO' are not the same.
2. Spaces count: 'Hello ' in 'Hello, World' would be False because of the extra space.
YA
Think of it as asking:
LI
Putting strings inside other strings is a common task in Python. Here are three simple ways to do it:
1. Using + (Concatenation)
You join strings using the + operator, but you must convert numbers to strings with str():
Aaliya Waseem,Dept.AIML,JNNCE
6
Introduction to python programming BPLCK105B
name = 'Al'
age = 4000
print('Hello, my name is ' + name + '. I am ' + str(age) + ' years old.')
E
The %s acts as a placeholder for values. Put the values in a tuple ( ) after the string:
C
name = 'Al'
N
age = 4000
JN
print('My name is %s. I am %s years old.' % (name, age))
L,
3. Using f-strings (Best and Easiest)
IM
Start the string with f and use {} to insert variables or expressions directly:
,A
name = 'Al'
M
age = 4000
EE
Key Point:
W
● Use f-strings for simplicity and readability. Don’t forget the f before the string
Here’s an easy guide to some helpful string methods, with examples to make things clear!
LI
1. Changing Case
AA
Examples:
Aaliya Waseem,Dept.AIML,JNNCE
7
Introduction to python programming BPLCK105B
Note: These methods don’t change the original string. If you want to save the result, assign it to a
variable:
2. Checking Case
E
Examples:
C
print("HELLO".isupper()) # True
N
print("hello".islower()) # True
JN
print("Hello123".islower()) # False (not all letters are lowercase)
L,
These methods check what a string is made of. They return True or False.
●
IM
isalpha(): Only letters, no spaces or numbers.
,A
● isalnum(): Letters and numbers only, no spaces.
● isdecimal(): Only numbers.
● isspace(): Only spaces, tabs, or newlines.
M
Examples:
print("hello".isalpha()) # True
AS
Examples:
5. Combining Methods
Aaliya Waseem,Dept.AIML,JNNCE
8
Introduction to python programming BPLCK105B
text = "Hello"
6. Real-Life Examples
E
print("I feel great too!")
else:
C
print("I hope your day gets better!")
N
Example 2: Validating Input
JN
while True:
age = input("Enter your age: ")
if age.isdecimal(): # Ensures input is only numbers
L,
break
print("Please enter a valid number.")
IM
while True:
password = input("Enter a password (letters and numbers only): ")
if password.isalnum(): # Ensures no special characters or spaces
,A
break
M
Aaliya Waseem,Dept.AIML,JNNCE
9
Introduction to python programming BPLCK105B
The join() method combines a list of strings into a single string, inserting a specified string between each
item.
How It Works:
● Called on a string: The string specifies what goes between each list item.
● Pass a list: Provide the list of strings you want to combine.
Examples:
E
# Join with a comma and space
C
print(', '.join(['cats', 'rats', 'bats'])) # Output: 'cats, rats, bats'
N
# Join with a space
JN
print(' '.join(['My', 'name', 'is', 'Simon'])) # Output: 'My name is Simon'
L,
print('ABC'.join(['My', 'name', 'is', 'Simon'])) # Output: 'MyABCnameABCisABCSimon'
Key Points:
IM
,A
● The string (', ', ' ', 'ABC') is inserted between each list item.
● The list must only contain strings, or you’ll get an error.
M
The split() method breaks a string into a list of smaller strings. By default, it splits wherever there’s
whitespace (spaces, tabs, newlines).
AS
How It Works:
W
Examples:
Key Points:
Aaliya Waseem,Dept.AIML,JNNCE
10
Introduction to python programming BPLCK105B
The split('\n') method splits a string into a list of lines. Each line ends where there’s a newline (\n).
Example:
spam = '''Dear Alice,
How have you been? I am fine.
E
There is a container in the fridge
that is labeled "Milk Experiment."
C
Please do not drink it.
N
Sincerely,
Bob'''
JN
# Split by newline characters
print(spam.split('\n'))
L,
Output:
IM
[
'Dear Alice,',
'How have you been? I am fine.',
,A
'There is a container in the fridge',
'that is labeled "Milk Experiment."',
'',
M
'Bob'
]
Each line becomes an item in the list. Empty lines are included as empty strings ('').
AS
W
YA
LI
AA
The partition() method splits a string into three parts based on a specific separator string you provide. It
creates a tuple with three parts:
Aaliya Waseem,Dept.AIML,JNNCE
11
Introduction to python programming BPLCK105B
How It Works:
E
○ The separator.
○ Text after the separator.
C
N
Examples:
JN
# Split using 'w' as the separator
print('Hello, world!'.partition('w'))
L,
# Output: ('Hello, ', 'w', 'orld!')
IM
# Split using 'world' as the separator
,A
print('Hello, world!'.partition('world'))
If the Separator Appears Multiple Times: The method only splits at the first occurrence of the
EE
separator.
print('Hello, world!'.partition('o'))
W
If the Separator Is Not Found: The whole string is returned as the first part, and the second and third
YA
print('Hello, world!'.partition('XYZ'))
AA
Assigning the Results to Variables: You can use multiple assignment to save the three parts in separate
variables.
Aaliya Waseem,Dept.AIML,JNNCE
12
Introduction to python programming BPLCK105B
E
● Quickly divide a string into before, separator, and after parts.
● Useful for tasks like splitting a sentence into its components or isolating specific sections of a
C
string.
N
In short, partition() makes it easy to break a string into three useful pieces based on a specific keyword or
JN
character
L,
These methods help you align text neatly by adding extra spaces (or other characters) to the left, right, or
IM
both sides of your string. This is super useful when formatting output like tables or lists. Let’s break it
down:
,A
rjust(): Right-Justify
● Adds spaces to the left of the string so the text is pushed to the right.
M
● The number you provide is the total length of the new string.
EE
Example:
print('Hello'.rjust(10))
AS
# Output: ' Hello' (5 spaces added on the left to make it 10 characters long)
W
print('Hello'.rjust(10, '*'))
YA
# Output: '*****Hello'
LI
ljust(): Left-Justify
AA
● Adds spaces to the right of the string so the text stays on the left.
● Again, the number you provide is the total length of the new string.
Example:
print('Hello'.ljust(10))
Aaliya Waseem,Dept.AIML,JNNCE
13
Introduction to python programming BPLCK105B
print('Hello'.ljust(10, '-'))
# Output: 'Hello-----'
● Adds spaces (or custom characters) to both sides of the string to center it.
● The total length of the resulting string is determined by the number you provide.
Example:
E
print('Hello'.center(10))
C
# Output: ' Hello ' (2 spaces on each side for a total of 10 characters)
N
JN
Use custom characters:
print('Hello'.center(10, '='))
L,
# Output: '==Hello==='
IM
7. PROJECT: ADDING BULLETS TO WIKI MARKUP
,A
This project teaches you how to create a Python program (bulletPointAdder.py) that automates adding
bullet points (*) to the start of each line of text. Here's how it works in simple terms:
M
1. Take text from the clipboard (the text you copied).
2. Add a star (*) at the start of every line.
3. Put the modified text back onto the clipboard so you can paste it anywhere.
AS
This is useful if you want to create a bulleted list for something like a Wikipedia article, but don’t want to
add * manually for each line.
W
How It Works:
YA
import pyperclip
Aaliya Waseem,Dept.AIML,JNNCE
14
Introduction to python programming BPLCK105B
Use the split('\n') method to split the text into a list of lines:t
E
lines = text.split('\n') # Break text into a list of lines
C
Loop through each line and add a star at the start:
N
JN
for i in range(len(lines)): # Loop through each line
lines[i] = '* ' + lines[i] # Add "* " at the start of each line
L,
Step 3: Combine the Lines Back Together
IM
Now that every line starts with a star, combine them back into a single string using '\n'.join(lines):
,A
text = '\n'.join(lines) # Combine the list into a single string with newlines
Finally, put the modified text (with bullets) back onto the clipboard so it’s ready to paste:
EE
Final Code:
import pyperclip
YA
text = pyperclip.paste()
LI
lines[i] = '* ' + lines[i] # Add a star to the start of the line
text = '\n'.join(lines)
Aaliya Waseem,Dept.AIML,JNNCE
15
Introduction to python programming BPLCK105B
pyperclip.copy(text)
● Remove spaces.
● Add numbers or custom symbols.
E
● Change the format of your text for specific tasks.
C
8. PROJECT : PASSWORD LOCKER
N
1. Start
JN
● The program begins its execution.
L,
2. Check Command-Line Arguments
IM
● The program checks if you have provided the account name (the account you want the password
for) as an input.
● If no account name is provided:
,A
○ The program displays a usage message like:
"Usage: python pw.py [account_name]"
M
and stops.
● If an account name is provided, it moves to the next step.
EE
● The program checks whether the provided account name exists in the password dictionary (where
all accounts and their passwords are stored).
W
○ The program copies the password to the clipboard using the pyperclip module.
○ It also prints a message like:
"Password for [account_name] copied to clipboard!"
LI
5. End
Aaliya Waseem,Dept.AIML,JNNCE
16
Introduction to python programming BPLCK105B
You Have Multiple Accounts Imagine you have passwords for different accounts like:
E
○ Email: email123password
○ Facebook: fb_secure2025
C
○ Twitter: tweet@secure!
N
You don’t want to memorize all these passwords. Instead, you’ve written a Python program called pw.py
JN
to store and retrieve these passwords securely.
How It Works: The program has a dictionary where the account names (like "email", "facebook",
"twitter") are the keys, and their passwords are the values.
L,
IM
PASSWORDS = {
"email": "email123password",
,A
"facebook": "fb_secure2025",
"twitter": "tweet@secure!"
}
M
Example: Retrieving a Password Let’s say you need the password for your Facebook account.
EE
Steps
Here, "facebook" is the account name you want the password for.
W
● The program checks if you provided an account name. Since you typed "facebook," it moves
forward.
● It looks in the dictionary for the "facebook" account.
LI
● Found it! The program copies fb_secure2025 to your clipboard (using the pyperclip module).
AA
The program will check for "instagram" in the dictionary but won’t find it.
Aaliya Waseem,Dept.AIML,JNNCE
17
Introduction to python programming BPLCK105B
What If You Forget to Provide an Account Name? If you just type: python pw.py
The program will notice you didn’t provide an account name and print:
Usage: python pw.py [account_name]
This reminds you to include the account name when running the program.
E
Summary
C
Command: python pw.py [account_name]
N
○ If the account exists: Copies the password and prints a success message.
JN
○ If the account doesn’t exist: Tells you the account isn’t found.
○ If no account name is provided: Shows usage instructions.
CHAPTER 8
L,
1. READING AND WRITING FILES
IM
Definition: A file path is the location of a file on your computer, like an address that tells your
,A
system where to find it. It consists of:
● Path: The hierarchy of folders that leads to the file (e.g., C:\Users\Al\Documents\document.txt).
EE
Concept
AS
W
YA
LI
AA
Aaliya Waseem,Dept.AIML,JNNCE
18
Introduction to python programming BPLCK105B
E
○ A Python module to handle paths easily.
○ Automatically adjusts the separator based on the operating system.
C
○ Uses the / operator to join paths (even on Windows).
N
Examples
JN
Basic Example of a File Path
L,
● Windows: C:\Users\Al\Documents\project.docx
● macOS/Linux: /Users/Al/Documents/project.docx
● Path: The location of the file on your computer, which includes the folder hierarchy. In Windows,
a path might look like C:\Users\asweigart\Documents\projects.docx. In other operating systems
like macOS or Linux, paths have a similar structure but may use different slashes (/).
YA
Aaliya Waseem,Dept.AIML,JNNCE
19
Introduction to python programming BPLCK105B
Opening an Existing File:Use functions or methods to open an existing file and perform read or write
operations.
E
with open('filename.txt', 'r') as file:
content = file.read()
C
N
4. Writing Data to a File: After opening a file in write mode ('w'), data can be written using functions
like write() or writelines().
JN
Example:
with open('filename.txt', 'w') as file:
file.write('Hello, world!')
L,
5. Appending to a File: Use 'a' mode to append data to an existing file.
Example:
IM
,A
with open('filename.txt', 'a') as file:
file.write('\nAppended text')
M
6. Reading Data from a File: Use read modes ('r', 'rb' for binary) to read data from files.
EE
Example:
with open('filename.txt', 'r') as file:
AS
content = file.read()
● Ensure paths are correctly specified based on the operating system (Windows, macOS, Linux).
● Example:
YA
8. Closing the File: Always close the file after reading or writing operations to free up system resources.
AA
Example:
file.close()
9. Error Handling: Handle errors such as file not found or permissions issues.
Example:
try:
with open('filename.txt', 'r') as file:
Aaliya Waseem,Dept.AIML,JNNCE
20
Introduction to python programming BPLCK105B
content = file.read()
except FileNotFoundError:
print("File not found.")
By following these steps, data can be stored in files and accessed or modified as needed even after the
program has stopped running.
Current Working Directory (cwd): Current Working Directory (cwd): This is the location from which a
E
program starts working. Any files or directories you refer to will be relative to this location unless a full
path is given.
C
N
Examples:
JN
os.getcwd() returns the current working directory.
import os
L,
os.getcwd()
IM
Changing the current working directory with os.chdir('path'):
os.chdir('C:\\Windows\\System32')
,A
If a file is named project.docx and your cwd is C:\Python34, then project.docx refers to
C:\Python34\project.docx.
M
os.chdir('C:\\ThisFolderDoesNotExist')
AS
Summary
● Current Working Directory (cwd) is where Python looks for files by default.
● Absolute Path includes the full path (e.g., C:\path\to\file.txt).
● Relative Path starts from cwd and uses . or .. to navigate directories.
Aaliya Waseem,Dept.AIML,JNNCE
21
Introduction to python programming BPLCK105B
E
C
N
JN
L,
3. OS PATH MODULE
IM
The os.path module in Python provides a variety of helpful functions for working with file paths. Let’s
break it down in an easy way with simple scenarios:
,A
1. Working with Absolute and Relative Paths
M
● Absolute Path: A full path from the root directory (e.g., C:\Users\username\Documents\file.txt).
● Relative Path: A path relative to the current working directory (e.g., file.txt if your cwd is
EE
C:\Users\username\Documents).
Scenario: Suppose you have a Python project and your current working directory (cwd) is C:\Python34.
AS
print(os.path.abspath('.\\Scripts'))
YA
Output: C:\Python34\Scripts
Scenario:You have a relative path ./Scripts and want to check if it’s absolute:
AA
import os
print(os.path.isabs('./Scripts'))
Output: False
Aaliya Waseem,Dept.AIML,JNNCE
22
Introduction to python programming BPLCK105B
Output: True
3. Relative Paths: Use os.path.relpath(path, start) to get a relative path from a starting point.
Scenario:
Output: 'Windows'
E
Now, if you want to go from C:\spam\eggs to C:\Windows:
C
print(os.path.relpath('C:\\Windows', 'C:\\spam\\eggs'))
N
Output: '..\\..\\Windows' (moving up two directories)
JN
4. Getting Directory Name and Base Name
L,
● os.path.basename(path) gives you everything after the last slash.
IM
Scenario:
,A
You have a file path C:\Windows\System32\calc.exe:
import os
M
path = 'C:\\Windows\\System32\\calc.exe'
print(os.path.dirname(path))
EE
print(os.path.basename(path))
Output:
AS
○ C:\Windows\System32
○ calc.exe
W
5. Combining Directory and Base Name: Use os.path.split(path) to get a tuple of the directory and base
name.
YA
Scenario:
Using C:\Windows\System32\calc.exe:
LI
import os
AA
calcFilePath = 'C:\\Windows\\System32\\calc.exe'
print(os.path.split(calcFilePath))
● Output:
○ Directory: C:\Windows\System32
○ Base name: calc.exe
6. Splitting a Path: path.split(os.path.sep) splits a path into its components based on the system’s file
separator (os.sep).
Scenario:
Aaliya Waseem,Dept.AIML,JNNCE
23
Introduction to python programming BPLCK105B
On Windows:
print(calcFilePath.split(os.path.sep))
● Output: ['C:', 'Windows', 'System32', 'calc.exe']
On macOS or Linux:
print('/usr/bin'.split(os.path.sep))
● Output: ['', 'usr', 'bin']
Summary
E
● Absolute Paths: Full paths from the root directory.
C
● Relative Paths: Paths relative to the current working directory.
N
● os.path functions help handle paths easily across different systems, checking if paths are absolute,
creating relative paths, and separating paths into directories and file names.
JN
4. THE FILE READING/WRITING PROCESS
L,
In Python, working with files involves three main steps: opening the file, performing read or write
operations, and then closing the file.
IM
1. Opening a File: To open a file, use the open() function.
,A
Syntax: file = open('filename.txt', mode)
● 'w' for write (creates a new file or overwrites if the file already exists).
● 'a' for append (adds content to the end of the file).
AS
Once the file is opened, use methods like read() or write() to interact with it.
content = file.read()
print(content)
Writing to a file:
Aaliya Waseem,Dept.AIML,JNNCE
24
Introduction to python programming BPLCK105B
Writing to a file:
file = open('example.txt', 'w')
E
file.write('New content')
file.close()
C
N
3. Closing the File: Always close the file after you finish reading or writing to it to free up system
resources.
JN
file.close()
L,
Scenario: After writing or reading:
IM
file = open('example.txt', 'r')
content = file.read()
print(content)
,A
file.close()
Summary
M
This process handles plaintext files such as .txt or .py files, where content is simple text.
W
In Python, you can open files using the open() function. Let's break it down step by step with simple
examples.
LI
1. Opening a File
AA
To open a file:
Example:
Aaliya Waseem,Dept.AIML,JNNCE
25
Introduction to python programming BPLCK105B
2. Reading Files
Once you have a File object, you can use different methods to read its contents:
a) read() Method
E
Example:
C
N
helloFile = open('hello.txt')
helloContent = helloFile.read()
JN
print(helloContent)
Output:
Hello world!
L,
b) readlines() Method
IM
● readlines() reads the file line by line and returns a list of strings, where each string represents a
,A
line.
Example:
M
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
AS
sonnetFile = open('sonnet29.txt')
sonnetLines = sonnetFile.readlines()
YA
print(sonnetLines)
Output:
LI
['When, in disgrace with fortune and men\'s eyes,\n', ' I all alone beweep my outcast state,\n', ' And trouble
AA
deaf heaven with my bootless cries,\n', ' And look upon myself and curse my fate,\n']
3. Closing the File: After you're done reading or writing to a file, always remember to close it to free up
system resources:
helloFile.close()
Summary
Aaliya Waseem,Dept.AIML,JNNCE
26
Introduction to python programming BPLCK105B
The shelve module in Python makes it easy to save and load data from your program so it doesn't get lost
when you close the program. It works like a magic storage box that saves data to your computer and lets
you retrieve it later.
E
Here’s how it works in simple terms:
C
Saving Data:
N
● You create a "shelf" (a special storage object) by calling shelve.open() and giving it a filename.
JN
This creates some hidden files on your computer to store the data.
● You can store your data in the shelf just like you’d store items in a dictionary. For example, you
can save a list of cat names using a key like 'cats'.
L,
● After saving your data, you must close the shelf to make sure everything is saved properly.
IM
Example:
import shelve
,A
shelfFile = shelve.open('mydata') # Open a shelf file named 'mydata'
cats = ['Zophie', 'Pooka', 'Simon'] # List of cat names
shelfFile['cats'] = cats # Save the list using the key 'cats'
M
Loading Data:
● You can open the shelf again later and retrieve the data using the same key.
AS
● The data you saved earlier will still be there, even after restarting your program or computer!
Example:
W
import shelve
shelfFile = shelve.open('mydata') # Open the same shelf file
print(shelfFile['cats']) # Get the list of cats
YA
Extra Features:
AA
● The shelf acts like a dictionary. You can use .keys() to see all the keys or .values() to see all the
saved data.
● If you want the keys or values as a real list, wrap them in list().
Example:
import shelve
shelfFile = shelve.open('mydata') # Open the shelf
print(list(shelfFile.keys())) # See all the keys
print(list(shelfFile.values())) # See all the values
Aaliya Waseem,Dept.AIML,JNNCE
27
Introduction to python programming BPLCK105B
shelfFile.close()
How It Works:
When you use shelve, it creates some hidden files (.bak, .dat, .dir on Windows or .db on Mac/Linux) to
store your data. These files are handled automatically, so you don’t need to worry about them.
Why Use a Shelve? It’s perfect for saving data that your program might need later, like settings, game
progress, or lists of items. It’s like saving notes in a file but easier because Python takes care of the tricky
parts for you!
E
Example for understanding purpose:
C
N
Imagine you’re running a cooking club and want to keep track of your favorite recipes. You don’t want to
write them down every time you reopen your notebook. Instead, you want to save them in a "digital box"
JN
that remembers them for you.
Day 1: Adding Recipes You decide to save some of your favorite recipes:
L,
● Spaghetti Carbonara
IM
● Chocolate Cake
● Caesar Salad
,A
You write these recipes down and store them in a special box (the shelve module). Once the recipes are
safely saved, you lock the box and leave for the day.
M
Day 2: Checking the Recipes The next day, you want to see the recipes you saved. You unlock the box,
look inside, and find your list exactly as you left it:
EE
● Spaghetti Carbonara
● Chocolate Cake
AS
● Caesar Salad
The box has remembered everything you stored the previous day!
W
Day 3: Adding a New Recipe You come across a new recipe for Banana Bread and decide to add it to
your collection. You unlock the box, add "Banana Bread" to the list, and lock it again.
YA
● Spaghetti Carbonara
AA
● Chocolate Cake
● Caesar Salad
● Banana Bread
Day 4: Showing the Recipes to a Friend Your friend asks about your recipes. You unlock the box, take
out the list, and show them:
● Spaghetti Carbonara
● Chocolate Cake
● Caesar Salad
Aaliya Waseem,Dept.AIML,JNNCE
28
Introduction to python programming BPLCK105B
● Banana Bread
E
3. Persistence
No matter how many days pass or how many times you open and close the box, the data you’ve
C
stored remains unchanged unless you update it.
N
4. Flexibility
You can add new recipes, view the existing ones, or even remove some if you no longer need
JN
them.
This scenario shows how the shelve module can be used to save and retrieve data in your programs, just
L,
like storing and managing items in a box.
IM
7. SAVING VARIABLES WITH THE PPRINT.PFORMAT() FUNCTION
The pprint.pformat() function in Python helps save data in a clean, easy-to-read format as Python code.
,A
Here's how it works, step by step:
○ It turns your data (like a list or dictionary) into a string that looks neat and is valid Python
code.
EE
● Now, whenever you need that data, you can import myCats and use the list in your programs.
AA
● Readable & Editable: The saved data is plain text, so you can open and edit it with any text editor.
● Limitations: This method works only for simple data types (e.g., numbers, strings, lists,
dictionaries) but not for complex objects like open files.
For most cases, shelve is better for saving data, but this method is handy when you need human-readable
and editable files.
Aaliya Waseem,Dept.AIML,JNNCE
29
Introduction to python programming BPLCK105B
Example: Imagine you have a list of fruits and want to save it for later use in your programs.
import pprint
# A list of fruits
fruits = ['apple', 'banana', 'cherry']
# Save the list to a Python file
with open('myFruits.py', 'w') as file:
file.write('fruits = ' + pprint.pformat(fruits) + '\n')
E
This creates a file called myFruits.py, and its content will look like this:
fruits = ['apple', 'banana', 'cherry']
C
N
Step 2: Use the Saved List in Another Program
JN
import myFruits
# Access the saved list of fruits
print(myFruits.fruits) # Output: ['apple', 'banana', 'cherry']
# Use the list
L,
for fruit in myFruits.fruits:
IM
print(f"I love {fruit}!")
Output:
,A
['apple', 'banana', 'cherry']
I love apple!
M
I love banana!
I love cherry!
EE
● The list is saved in a file you can import and reuse in other programs.
● You can open myFruits.py in any text editor to view or edit the fruits list.
W
Imagine you're a teacher and you want to create unique quiz files for your students so they can’t copy
YA
each other’s answers. Here’s how you can do it step by step using Python:
First, you create a dictionary that contains the states and their capitals:
AA
capitals = {
'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
# ... more states and capitals ...
}
This is the "question bank" for your quiz.
Aaliya Waseem,Dept.AIML,JNNCE
30
Introduction to python programming BPLCK105B
Decide how many quizzes you want (e.g., 35 quizzes). For each quiz, you:
E
import random
C
states = list(capitals.keys()) # Get the list of states
N
random.shuffle(states) # Shuffle them randomly
This ensures every quiz has questions in a different order.
JN
Step 4: Create Questions and Options
L,
1. Pick the correct capital for the state.
IM
2. Randomly select three wrong answers from the list of all capitals.
3. Combine the correct answer and wrong answers into a list.
,A
4. Shuffle the list so the correct answer isn’t always in the same position.
Example:
M
quizFile.write("\n")
correct_letter = 'ABCD'[answer_options.index(correct_answer)]
Aaliya Waseem,Dept.AIML,JNNCE
31
Introduction to python programming BPLCK105B
Repeat the above steps for all 50 states in each quiz and for all 35 quizzes.
● 35 quiz files with randomized questions and options (e.g., capitalsquiz1.txt, capitalsquiz2.txt).
● 35 answer key files with the correct answers (e.g., capitalsquiz_answers1.txt,
E
capitalsquiz_answers2.txt).
C
Why Is This Useful?
N
● Unique Quizzes: Prevent cheating by randomizing questions and answers.
JN
● Easy to Create: Python automates repetitive work.
● Reusable: You can update the data (e.g., new states or topics) and generate new quizzes easily.
This way, Python helps you create professional, randomized quizzes quickly
L,
9. PROJECT: MULTI CLIPBOARD
1. What is a Multiclipboard?
IM
,A
A multiclipboard is a program that allows you to save multiple pieces of text with keywords and quickly
retrieve them whenever needed. Think of it as a clipboard with superpowers, where you can store several
M
pieces of text at once and retrieve any of them using specific names (keywords).
EE
● sys.argv: Reads command-line arguments you enter when running the program.
YA
We start by:
Aaliya Waseem,Dept.AIML,JNNCE
32
Introduction to python programming BPLCK105B
○ A shelf file acts as a small database where we save keywords and their corresponding
clipboard content.
The program:
E
1. Checks if the first argument is save and there’s a second argument (<keyword>).
C
2. Copies the current clipboard content.
N
3. Saves it into the shelf file using <keyword> as the key.
JN
For example:
L,
● Now "greeting" is saved as the keyword for "Hello, world!"
IM
Step 3: Listing All Keywords
,A
When you type the command:
py mcb.pyw list
M
The program:
EE
3. You can paste the list into a text editor to view the keywords.
For example: If you have saved greeting and farewell, running list will copy:
W
['greeting', 'farewell']
YA
py mcb.pyw <keyword>
AA
The program:
For example:
Aaliya Waseem,Dept.AIML,JNNCE
33
Introduction to python programming BPLCK105B
E
● Automates repetitive tasks, such as filling out forms.
● Saves time when working with frequently used text snippets.
C
● Makes it easy to organize and manage multiple pieces of clipboard content.
N
JN
L,
IM
,A
M
EE
AS
W
YA
LI
AA
Aaliya Waseem,Dept.AIML,JNNCE
34