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 [Link]
Module, The File Reading/Writing Process, Saving Variables with the shelve Module,Saving Variables
JNNCE
DEFINITION: In programming, a string is a sequence of characters enclosed in quotation marks. These
characters can be letters, numbers, symbols, or whitespace.
Types of Strings:
1. Single-quoted strings:
○ Created using single quotes (' ')
○ Example: 'Hello'
2. Double-quoted strings:
○ Created using double quotes (" ")
○ Example: "World"
3. Raw strings:
○ Created by prefixing the string with r or R (e.g., r'...' or R'...').
○ These strings treat backslashes as literal characters and not escape characters.
○ Example: r'C:\Users\Al'
4. Multiline strings:
○ Created using triple quotes (''' or """).
○ Used for strings that span multiple lines.
Example:
'''This is a
multiline string.'''
String Example:
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,[Link],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."
JNNCE
Escape Characters: Sometimes, you need special characters inside a string, such as quotes, backslashes,
or new lines. This is where escape characters come in.
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.
A
spam = "He said, \"Hi!\""
path = 'C:\\Users\\Alice'
# New line
poem = 'Roses are red,\nViolets are blue.'
# Tab
tabbed_text = 'Name\tAge\tLocation'
Conclusion
This makes it easy to include complex text in Python strings without errors.
Raw Strings: A raw string is a string where Python ignores all escape characters. This means that
backslashes are treated as part of the string, not as escape characters.
Why use raw strings? When working with strings that contain many backslashes, such as file paths or
regular expressions.
print(r'C:\Users\Al\Desktop')
Output: C:\Users\Al\Desktop
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
characters, you can use triple quotes.
● Begins and ends with three single quotes ''' or three double quotes """.
● All lines within the triple quotes are considered part of the string.
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,[Link],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''')
JNNCE
Sincerely,
Bob
Using Triple Quotes for Comments: Multiline strings can also be used for comments that span multiple
lines.
Example:
# Regular comment
print('Hello!') # This is a single-line comment
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.
Here’s how the string "Hello, world!" looks with its index numbers:
If you want to grab just one character, you can use its index like this:
Aaliya Waseem,[Link],JNNCE
4
Introduction to python programming BPLCK105B
WASEEM, AIML,
Slicing (Getting Parts of the String)
JNNCE
You can also take parts of the string by slicing it. To slice, you give a starting index and an ending
index like this:
So spam[0:5] means:
Start at position 0 (H), go up to (but not include) position 5.
If you don’t give a starting or ending index, Python assumes some defaults:
A position 7)
AALIY
Original String Stays the Same
When you slice a string, Python gives you a copy of the part you asked for. The original string doesn’t
change:
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,[Link],JNNCE
5
Introduction to python programming BPLCK105B
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.
JNNCE
The in operator checks if a smaller string (a substring) is inside a bigger string.
If the smaller string is found, the result is True. If it’s not found, the result is False.
Examples:
everywhere
The not in operator checks if a smaller string is not inside a bigger string.
If the smaller string is not found, the result is True. If it’s found, the result is False.
Examples:
print('cats' not in 'cats and dogs') # False, because 'cats' *is* inside 'cats and
dogs' print('fish' not in 'cats and dogs') # True, because 'fish' is not in 'cats
Think of it as asking:
Putting strings inside other strings is a common task in Python. Here are three simple ways to do it:
1. Using + (Concatenation)
Aaliya Waseem,[Link],JNNCE
6
Introduction to python programming BPLCK105B
You join strings using the + operator, but you must convert numbers to strings with str():
Aaliya Waseem,[Link],JNNCE
7
Introduction to python programming BPLCK105B
name = 'Al'
age = 4000
print('Hello, my name is ' + name + '. I am ' + str(age) + ' years old.')
WASEEM, AIML,
2. Using %s (String Interpolation)
The %s acts as a placeholder for values. Put the values in a tuple ( ) after the string:
name = 'Al'
age = 4000
JNNCE
print('My name is %s. I am %s years old.' % (name, age))
Start the string with f and use {} to insert variables or expressions directly:
name = 'Al'
age = 4000
Key Point:
● Use f-strings for simplicity and readability. Don’t forget the f before the string
A
AALIY
6. USEFUL STRING METHODS
Here’s an easy guide to some helpful string methods, with examples to make things clear!
1. Changing Case
Examples:
Aaliya Waseem,[Link],JNNCE
8
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
A WASEEM, AIML,
● islower(): Checks if all letters are lowercase.
Examples:
JNNCE
print("HELLO".isupper()) # True
print("hello".islower()) # True
These methods check what a string is made of. They return True or False.
Examples:
print("hello".isalpha()) # True
print("hello123".isalpha()) # False (contains numbers)
print("hello123".isalnum()) # True
print("12345".isdecimal()) # True
print(" ".isspace()) # True
print("This Is Title Case".istitle()) # True
Y
AAL
4. Checking Start and End
I
Examples:
5. Combining Methods
Aaliya Waseem,[Link],JNNCE
9
Introduction to python programming BPLCK105B
text = "Hello"
6. Real-Life Examples
JNNCE
else:
print("I hope your day gets better!")
Aaliya Waseem,[Link],JNNCE
10
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.
JNNCE
print(', '.join(['cats', 'rats', 'bats'])) # Output: 'cats, rats, bats'
Key Points:
● The string (', ', ' ', 'ABC') is inserted between each list item.
● The list must only contain strings, or you’ll get an error.
The split() method breaks a string into a list of smaller strings. By default, it splits wherever there’s
whitespace (spaces, tabs, newlines).
How It Works:
Examples:
Key Points:
Aaliya Waseem,[Link],JNNCE
11
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:
JNNCE
that is labeled "Milk Experiment."
Please do not drink it.
Sincerely,
Bob'''
# Split by newline characters
print([Link]('\n'))
Output:
[
'Dear Alice,',
'How have you been? I am fine.',
'There is a container in the fridge',
'that is labeled "Milk Experiment."',
'',
'Please do not drink it.',
'Sincerely,',
'Bob'
]
Each line becomes an item in the list. Empty lines are included as empty strings ('').
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,[Link],JNNCE
12
Introduction to python programming BPLCK105B
How It Works:
WASEEM, AIML,
3. Returns a tuple with:
○ Text before the separator.
○ The separator.
JNNCE
○ Text after the separator.
Examples:
print('Hello, world!'.partition('w'))
print('Hello, world!'.partition('world'))
If the Separator Appears Multiple Times: The method only splits at the first occurrence of the
separator.
print('Hello, world!'.partition('o'))
A
AALIY
If the Separator Is Not Found: The whole string is returned as the first part, and the second and third
parts are empty strings.
print('Hello, world!'.partition('XYZ'))
Assigning the Results to Variables: You can use multiple assignment to save the three parts in separate
variables.
Aaliya Waseem,[Link],JNNCE
13
Introduction to python programming BPLCK105B
JNNCE
● Useful for tasks like splitting a sentence into its components or isolating specific sections of a
string.
In short, partition() makes it easy to break a string into three useful pieces based on a specific keyword
or character
These methods help you align text neatly by adding extra spaces (or other characters) to the left, right, or
both sides of your string. This is super useful when formatting output like tables or lists. Let’s break it
down:
rjust(): Right-Justify
● Adds spaces to the left of the string so the text is pushed to the right.
● The number you provide is the total length of the new string.
Example:
print('Hello'.rjust(10))
# Output: ' Hello' (5 spaces added on the left to make it 10 characters long)
print('Hello'.rjust(10, '*'))
# Output: '*****Hello'
ljust(): Left-Justify
● 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,[Link],JNNCE
14
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:
A WASEEM, AIML,
JNNCE
print('Hello'.center(10))
# Output: ' Hello ' (2 spaces on each side for a total of 10 characters)
print('Hello'.center(10, '='))
# Output: '==Hello==='
This project teaches you how to create a Python program ([Link]) that automates adding
bullet points (*) to the start of each line of text. Here's how it works in simple terms:
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.
How It Works:
Y
Step 1: Copy and Paste from the Clipboard
AAL
Python has a library called pyperclip that lets you:
I
● Get text from the clipboard using [Link]().
● Put text back onto the clipboard using [Link]().
import pyperclip
Aaliya Waseem,[Link],JNNCE
15
Introduction to python programming BPLCK105B
JNNCE
lines = [Link]('\n') # Break text into a list of lines
lines[i] = '* ' + lines[i] # Add "* " at the start of each line
Now that every line starts with a star, combine them back into a single string using '\n'.join(lines):
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:
Final Code:
import pyperclip
text = [Link]()
lines[i] = '* ' + lines[i] # Add a star to the start of the line
text = '\n'.join(lines)
Aaliya Waseem,[Link],JNNCE
16
Introduction to python programming BPLCK105B
[Link](text)
JNNCE
8. PROJECT : PASSWORD LOCKER
1. Start
● 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:
○ The program displays a usage message
like: "Usage: python [Link]
[account_name]" and stops.
● If an account name is provided, it moves to the next step.
● The program checks whether the provided account name exists in the password dictionary (where
all accounts and their passwords are stored).
5. End
Aaliya Waseem,[Link],JNNCE
17
Introduction to python programming BPLCK105B
○ Email: email123password
JNNCE
○ Facebook: fb_secure2025
○ Twitter: tweet@secure!
You don’t want to memorize all these passwords. Instead, you’ve written a Python program called
[Link] 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.
PASSWORDS = {
"email": "email123password",
"facebook": "fb_secure2025",
"twitter": "tweet@secure!"
}
Example: Retrieving a Password Let’s say you need the password for your Facebook account.
Steps
Here, "facebook" is the account name you want the password for.
● 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.
● Found it! The program copies fb_secure2025 to your clipboard (using the pyperclip module).
The program will check for "instagram" in the dictionary but won’t find it.
Aaliya Waseem,[Link],JNNCE
18
Introduction to python programming BPLCK105B
What If You Forget to Provide an Account Name? If you just type: python [Link]
The program will notice you didn’t provide an account name and print:
Usage: python [Link] [account_name]
WASEEM, AIML,
This reminds you to include the account name when running the program.
Summary
JNNCE
Command: python [Link] [account_name]
○ If the account exists: Copies the password and prints a success message.
○ If the account doesn’t exist: Tells you the account isn’t found.
○ If no account name is provided: Shows usage instructions.
CHAPTER 8
Definition: A file path is the location of a file on your computer, like an address that tells your
system where to find it. It consists of:
Concept
AALIY
A
1. File Extensions:
○ The part after the last dot in the filename (e.g., .txt, .docx).
○ Tells what type of file it is (e.g., .docx for Word documents, .png for images).
2. Path Structure:
○ Root Folder: The starting point of the path.
■ Windows: C:\
■ macOS/Linux: /
Aaliya Waseem,[Link],JNNCE
19
Introduction to python programming BPLCK105B
JNNCE
○ Automatically adjusts the separator based on the operating system.
○ Uses the / operator to join paths (even on Windows).
Examples
● Windows: C:\Users\Al\Documents\[Link]
● macOS/Linux: /Users/Al/Documents/[Link]
1. Cross-Platform:
○ Works on Windows, macOS, and Linux without worrying about slashes.
2. Readable Code:
○ The / operator makes paths easy to join.
3. Error Prevention:
○ Avoids common bugs caused by manually adding slashes or using [Link].
Aaliya Waseem,[Link],JNNCE
20
Introduction to python programming BPLCK105B
Opening an Existing File:Use functions or methods to open an existing file and perform read or write
operations.
JNNCE
content = [Link]()
4. Writing Data to a File: After opening a file in write mode ('w'), data can be written using
functions like write() or writelines().
Example:
with open('[Link]', 'w') as file:
[Link]('Hello, world!')
Example:
6. Reading Data from a File: Use read modes ('r', 'rb' for binary) to read data from files.
Example:
with open('[Link]', 'r') as file:
content = [Link]()
● Ensure paths are correctly specified based on the operating system (Windows, macOS, Linux).
● Example:
○ Windows path: C:\Users\username\Documents\[Link]
○ macOS/Linux path: /Users/username/Documents/[Link]
8. Closing the File: Always close the file after reading or writing operations to free up system resources.
Example:
[Link]()
9. Error Handling: Handle errors such as file not found or permissions issues.
Example:
try:
with open('[Link]', 'r') as file:
Aaliya Waseem,[Link],JNNCE
21
Introduction to python programming BPLCK105B
content = [Link]()
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.
JNNCE
path is given.
Examples:
[Link]()
Windows\\System32')
If a file is named [Link] and your cwd is C:\Python34, then [Link] refers to
C:\Python34\[Link].
Error Example: Trying to change to a non-existent directory will result in an error. [Link]('C:\\
ThisFolderDoesNotExist')
1. Absolute Path:
○ Starts from the root folder (e.g., C:\Users\username\Documents\[Link]).
2. Relative Path:
○ Starts from the current working directory.
○ Example: [Link] if cwd is C:\Python34.
A L
Dot (.) and Dot-dot (..)
A 2. Dot-dot (..): Refers to "the parent folder" (the directory one level above).
○ Example: ..\[Link] when cwd is C:\Python34 refers to C:\[Link].
Summary
● Current Working Directory (cwd) is where Python looks for files by default.
● Absolute Path includes the full path (e.g., C:\path\to\[Link]).
● Relative Path starts from cwd and uses . or .. to navigate directories.
Aaliya Waseem,[Link],JNNCE
22
Introduction to python programming BPLCK105B
The [Link] 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:
● Absolute Path: A full path from the root directory (e.g., C:\Users\username\Documents\[Link]).
● Relative Path: A path relative to the current working directory (e.g., [Link] if your cwd is
C:\Users\username\Documents).
Scenario: Suppose you have a Python project and your current working directory (cwd) is C:\Python34.
print([Link]('.\\
I
Python34\Scripts
absolute: import os
print([Link]('./Scripts'))
Output: False
Output: True
3. Relative Paths: Use [Link](path, start) to get a relative path from a starting point.
Scenario:
JNNCE
Now, if you want to go from C:\spam\eggs to C:\Windows:
print([Link]('C:\\Windows', 'C:\\spam\\eggs'))
Scenario:
import os
path = 'C:\\Windows\\System32\\
[Link]' print([Link](path))
print([Link](path))
Output:
○ C:\Windows\System32
○ [Link]
5. Combining Directory and Base Name: Use [Link](path) to get a tuple of the directory and base
name.
Scenario:
Using C:\Windows\System32\[Link]:
import os
calcFilePath = 'C:\\Windows\\System32\\
[Link]' print([Link](calcFilePath))
● Output:
○ Directory: C:\Windows\System32
○ Base name: [Link]
6. Splitting a Path: [Link]([Link]) splits a path into its components based on the system’s file
separator ([Link]).
Scenario:
Aaliya Waseem,[Link],JNNCE
24
Introduction to python programming BPLCK105B
On Windows:
print([Link]([Link]))
● Output: ['C:', 'Windows', 'System32', '[Link]']
On macOS or Linux:
print('/usr/bin'.split([Link]))
● Output: ['', 'usr', 'bin']
JNNCE
● Absolute Paths: Full paths from the root directory.
● Relative Paths: Paths relative to the current working directory.
● [Link] functions help handle paths easily across different systems, checking if paths are absolute,
creating relative paths, and separating paths into directories and file names.
In Python, working with files involves three main steps: opening the file, performing read or write
operations, and then closing the file.
Once the file is opened, use methods like read() or write() to interact with it.
content = [Link]()
print(content)
Writing to a file:
[Link]('Hello, world!')
Aaliya Waseem,[Link],JNNCE
25
Introduction to python programming BPLCK105B
Writing to a file:
WASEEM, AIML,
file = open('[Link]', 'w')
[Link]('New content')
JNNCE
[Link]()
3. Closing the File: Always close the file after you finish reading or writing to it to free up
system resources.
[Link]()
Summary
This process handles plaintext files such as .txt or .py files, where content is simple text.
A
LIY
5. OPENING AND READING FILES IN PYTHON
In Python, you can open files using the open() function. Let's break it down step by step with simple
examples.
AA
1. Opening a File
To open a file:
Example:
Aaliya Waseem,[Link],JNNCE
26
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
JNNCE
Example:
helloFile = open('[Link]')
helloContent = [Link]()
print(helloContent)
Output:
Hello world!
b) readlines() Method
● readlines() reads the file line by line and returns a list of strings, where each string represents
a line.
Example:
sonnetFile = open('[Link]')
sonnetLines = [Link]()
print(sonnetLines)
Output:
['When, in disgrace with fortune and men\'s eyes,\n', ' I all alone beweep my outcast state,\n', ' And trouble
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:
[Link]()
Summary
Aaliya Waseem,[Link],JNNCE
27
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
JNNCE
Saving Data:
● You create a "shelf" (a special storage object) by calling [Link]() and giving it a filename.
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'.
● After saving your data, you must close the shelf to make sure everything is saved properly.
Example:
import shelve
shelfFile = [Link]('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' [Link]() # Close the shelf
Loading Data:
● You can open the shelf again later and retrieve the data using the same key.
● The data you saved earlier will still be there, even after restarting your program or computer!
Example:
import shelve
shelfFile = [Link]('mydata') # Open the same shelf file
print(shelfFile['cats']) # Get the list of cats
[Link]() # Close the shelf
Extra Features:
● 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 = [Link]('mydata') # Open the shelf
print(list([Link]())) # See all the keys
print(list([Link]())) # See all the values
Aaliya Waseem,[Link],JNNCE
28
Introduction to python programming BPLCK105B
[Link]()
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
JNNCE
Example for understanding purpose:
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"
that remembers them for you.
Day 1: Adding Recipes You decide to save some of your favorite recipes:
● Spaghetti Carbonara
● Chocolate Cake
● Caesar Salad
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.
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:
● Spaghetti Carbonara
● Chocolate Cake
● Caesar Salad
The box has remembered everything you stored the previous day!
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.
● Spaghetti Carbonara
● 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,[Link],JNNCE
29
Introduction to python programming BPLCK105B
● Banana Bread
stays safe.
3. Persistence
L, JNNCE
To access your saved data, you open the box. When you're done, you close it to ensure everything
No matter how many days pass or how many times you open and close the box, the data you’ve stored
remains unchanged unless you update it.
4. Flexibility
You can add new recipes, view the existing ones, or even remove some if you no longer need
them.
This scenario shows how the shelve module can be used to save and retrieve data in your programs,
M
just like storing and managing items in a box.
AALIYA WASEEM,
7. SAVING VARIABLES WITH THE [Link]() FUNCTION
The [Link]() function in Python helps save data in a clean, easy-to-read format as Python
AI
code. Here's how it works, step by step:
1. Pretty Formatting:
○ It turns your data (like a list or dictionary) into a string that looks neat and is valid
Python code.
2. Saving as a Python File:
○ You can write this formatted string to a .py file. This creates a Python script that
stores your data.
3. Using the Saved Data:
○ Later, you can import the .py file as a module to access the saved data, just like any
other Python script.
● 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,[Link],JNNCE
30
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
JNNCE
This creates a file called [Link], and its content will look like this:
fruits = ['apple', 'banana', 'cherry']
import myFruits
# Access the saved list of fruits
print([Link]) # Output: ['apple', 'banana', 'cherry']
# Use the list
for fruit in [Link]:
print(f"I love {fruit}!")
Output:
● The list is saved in a file you can import and reuse in other programs.
● You can open [Link] in any text editor to view or edit the fruits list.
Imagine you're a teacher and you want to create unique quiz files for your students so they can’t copy
each other’s answers. Here’s how you can do it step by step using Python:
A L
Step 1: Set Up the Data
First, you create a dictionary that contains the states and their capitals:
A
capitals = {
'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
# ... more states and capitals ...
}
This is the "question bank" for your quiz.
Aaliya Waseem,[Link],JNNCE
31
Introduction to python programming BPLCK105B
Decide how many quizzes you want (e.g., 35 quizzes). For each quiz, you:
JNNCE
import random
states = list([Link]()) # Get the list of states
[Link](states) # Shuffle them randomly
This ensures every quiz has questions in a different
order.
Example:
[Link]("\n")
correct_letter = 'ABCD'[answer_options.index(correct_answer)]
Aaliya Waseem,[Link],JNNCE
32
Introduction to python programming BPLCK105B
Repeat the above steps for all 50 states in each quiz and for all 35 quizzes.
JNNCE
Why Is This Useful?
This way, Python helps you create professional, randomized quizzes quickly
1. What is a Multiclipboard?
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
pieces of text at once and retrieve any of them using specific names (keywords).
● [Link]: Reads command-line arguments you enter when running the program.
● pyperclip: Allows the program to interact with the clipboard (copy/paste).
● shelve: A Python module for saving data persistently, like a lightweight database.
AA
4. How It Works (Step by Step)
Aaliya Waseem,[Link],JNNCE
33
Introduction to python programming BPLCK105B
○ A shelf file acts as a small database where we save keywords and their
corresponding clipboard content.
The program:
A WASEEM, AIML,
JNNCE
1. Checks if the first argument is save and there’s a second argument (<keyword>).
2. Copies the current clipboard content.
3. Saves it into the shelf file using <keyword> as the key.
For example:
py [Link] list
The program:
For example: If you have saved greeting and farewell, running list will copy:
['greeting', 'farewell']
Y
Step 4: Retrieving Clipboard Content
AAL
When you type the command:
I
py [Link] <keyword>
The program:
For example:
Aaliya Waseem,[Link],JNNCE
34
Introduction to python programming BPLCK105B
JNNCE
● Saves time when working with frequently used text snippets.
● Makes it easy to organize and manage multiple pieces of clipboard content.
Aaliya Waseem,[Link],JNNCE
35