0% found this document useful (0 votes)
5 views25 pages

Python Module 3

This document is a syllabus for a Python programming course, focusing on string manipulation and file handling. It covers topics such as string literals, escape characters, string methods, and file reading/writing processes, along with practical projects. The document also includes examples and explanations of various string methods and their applications in Python programming.

Uploaded by

yashatwood
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)
5 views25 pages

Python Module 3

This document is a syllabus for a Python programming course, focusing on string manipulation and file handling. It covers topics such as string literals, escape characters, string methods, and file reading/writing processes, along with practical projects. The document also includes examples and explanations of various string methods and their applications in Python programming.

Uploaded by

yashatwood
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
You are on page 1/ 25

Introduction to Python Programming - 22PLC105B/205B

MODULE 3
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: Multiclipboard

Chapter 1: Manipulating Strings - working with Strings


• Let’s look at some of the ways Python lets you write, print, and access strings in your
code.

1.1 String Literals


• Typing string values in Python code is fairly straightforward: They begin and end with
a single quote.

How can you use a quote inside a string?


Example:
• Typing 'That is Alice's cat.' won’t work,

• Because Python thinks the string ends after Alice, and the rest (s cat.') is invalid
Python code.

Solution:
• Double Quotes

• spam = “That is Alice's cat.” → if you need to use both single quotes and double
quotes in the string, you’ll need to use escape characters.

1.2 Escape Characters


An escape character lets you use characters that are otherwise impossible to put into a
string.
An escape character consists of a backslash (\) followed by the character you want to
add to the string.
Example 1:
Spam = 'Say hi to Bob\'s mother.’

Below table lists the escape characters you can use


1
Introduction to Python Programming - 22PLC105B/205B

Escape character Prints as

\' Single quote

\" Double quote

\t Tab

\n Newline (line break)

\\ Backslash

Example 2:
>>> print("Hello there!\nHow are you?\nI\'m doing fine.")
Output:
Hello there!
How are you?
I'm doing fine.

1.3 Raw Strings


• You can place an r before the beginning quotation mark of a string to make it a
raw string.
• A raw string completely ignores all escape characters and prints any backslash
that appears in the string.
Example:
>>> print(r'That is Carol\'s cat.')
Output:
That is Carol\'s cat.

• Because this is a raw string, Python considers the backslash as part of the string and not
as the start of an escape character.

1.4 Multiline Strings with triple Quotes


• While you can use the \n escape character to put a newline into a string, it is
often easier to use multiline strings.
• A multiline string in Python begins and ends with either three single quotes or
three double quotes.
• Any quotes, tabs, or newlines in between the “triple quotes” are considered part
of the string. Python’s indentation rules for blocks do not apply to lines inside
a multiline string.
Example:

2
Introduction to Python Programming - 22PLC105B/205B

print('''Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely, Bob''')

Output:

Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely, Bob
Note:

Below print statement gives you same output as above (Execute and Check)

print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and
extortion.\n\nSincerely,\nBob')

1.5 Multiline Comments


• While the hash character (#) marks the beginning of a comment for the rest of
the line, a multiline string is often used for comments that span multiple lines.
• The following is perfectly valid Python code:
"""This is a test Python program.
Written by Al Sweigart [email protected]
This program was designed for Python 3, not Python 2.
"""
def spam():
"""This is a multiline comment to help
explain what the spam() function does."""
print('Hello!')
1.6 Indexing and Slicing Strings
• Strings use indexes and slices the same way lists do.

Example
' H e l l o w o r l d ! '
0 1 2 3 4 5 6 7 8 9 10 11
• The space and exclamation point are included in the character count, so 'Hello world!'
is 12 characters long, from H at index 0 to ! at index 11.
Examples:
>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]

3
Introduction to Python Programming - 22PLC105B/205B

'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello‘
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'

1.7 The in and not in Operators with Strings


>>> 'Hello' in 'Hello World'
True
>>> 'Hello' in 'Hello'
True
>>> 'HELLO' in 'Hello World'
False
>>> '' in 'spam'
True
>>> 'cats' not in 'cats and dogs'
False

1.8 Useful String methods


upper()
lower()
isupper()
islower()

1.8.1 upper() and lower()


• The upper() and lower() string methods return a new string where all the letters in the
original string have been converted to uppercase or lowercase, respectively.
• Nonletter characters in the string remain unchanged.

Example 1:
>>> spam = 'Hello world!'
>>> spam = spam.upper()
>>> spam

'HELLO WORLD!'
>>> spam = spam.lower()

4
Introduction to Python Programming - 22PLC105B/205B

>>> spam

'hello world!'

Note:
• These methods do not change the string itself but return new string values.
• If you want to change the original string, you have to call upper() or lower() on the
string and then assign the new string to the variable where the original was stored.

• This is why you must use spam = spam.upper() to change the string in spam instead of
simply spam.upper().

Example 2:
print('How are you?')
feeling = input()

if feeling.lower() == 'great':
print('I feel great too.')
else:

print('I hope the rest of your day is good.')

OUTPUT:

How are you?


GREat
I feel great too.

1.8.2 isupper() and islower()


• isupper() returns → True- If all characters in the string are uppercase.
False- If the string contains 1 or more non-uppercase characters.
• islower() returns → True- If all characters in the string are lower.
False- If the string contains 1 or more non-lowercase characters.

Example 1:
>>> spam = 'Hello world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True

5
Introduction to Python Programming - 22PLC105B/205B

>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False

Example 2:
>>> 'Hello'.upper()
'HELLO'
>>> 'Hello'.upper().lower()
'hello'
>>> 'Hello'.upper().lower().upper()
'HELLO'
>>> 'HELLO'.lower()
'hello'
>>> 'HELLO'.lower().islower()
True

1.9 The isX String Methods


isalpha() returns True if the string consists only of letters and is not blank.
isalnum() returns True if the string consists only of letters and numbers and is not blank.
isdecimal() returns True if the string consists only of numeric characters and is not
blank.
isspace() returns True if the string consists only of spaces, tabs, and newlines and is not
blank.
istitle() method checks whether each word's first character is upper case and the rest are
in lower case or not. It returns True if a string is titlecased; otherwise, it returns False.
The symbols and numbers are ignored.
Example 1:

>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False

>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()

6
Introduction to Python Programming - 22PLC105B/205B

True

>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> 'This Is Title Case'.istitle()
True

>>> 'This Is Title Case 123'.istitle()


True

>>> 'This Is not Title Case'.istitle()


False
>>> 'This Is NOT Title Case Either'.istitle()

False

1.10 Program repeatedly asks users for their age and a password until
they provide valid input.
while True:

print('Enter your age:')


age = input()

if age.isdecimal():
break

print('Please enter a number for your age.')


while True:

print('Select a new password (letters and numbers only):')


password = input()
if password.isalnum():
break

print('Passwords can only have letters and numbers.')

Output:

7
Introduction to Python Programming - 22PLC105B/205B

Enter your age: forty two

Please enter a number for your age.


Enter your age: 42

Select a new password (letters and numbers only): secr3t!


Passwords can only have letters and numbers.
Select a new password (letters and numbers only): secr3t

1.11 The startswith() and endswith() String Methods


• The startswith() and endswith() methods return True if the string value they are
called on begins or ends (respectively) with the string passed to the method;
otherwise, they return False.
Example:
>>> 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'abc123'.endswith('12')
False
>>> 'Hello world!'.startswith('Hello world!')
True
>>> 'Hello world!'.endswith('Hello world!')
True
1.12 The join() and split() String Methods
• The join() method is useful when you have a list of strings that need to be joined
together into a single string value.
• The join() method is called on a string, gets passed a list of strings, and returns a
string.
• The returned string is the concatenation of each string in the passed-in list.

Example:
>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'

8
Introduction to Python Programming - 22PLC105B/205B

Example: The split() method does the opposite: It’s called on a string value and returns
a list of strings.
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']

1.13 Justifying Text with rjust(), ljust(), and center()


• The rjust() and ljust() string methods return a padded(Inserting non-
informative characters to a string is known as Padding) version of the string
they are called on, with spaces inserted to justify the text.
• The first argument to both methods is an integer length for the justified.
Example 1:
>>> 'Hello'.rjust(10)
‘ Hello’
>>> 'Hello'.rjust(20)
‘ Hello’
>>> 'Hello World'.rjust(20)
‘ Hello World’
>>> 'Hello'.ljust(10)
‘Hello ‘

NOTE:
'Hello'.rjust(10) says that we want to right-justify 'Hello' in a string of total length 10.
'Hello' is five characters, so five spaces will be added to its left, giving us a string of 10
characters with 'Hello' justified right.

Example 2:
>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello -------------- '
>>> 'Hello'.center(20)
‘ Hello '
>>> 'Hello'.center(20, '=')
‘=======Hello========'
NOTE:
The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right.

9
Introduction to Python Programming - 22PLC105B/205B

Program:
def print Picnic(items Dict, left Width, right Width):
print('PICNIC ITEMS'. center(left Width + right Width, '-
'))for k, v in items Dict. items():
print(k. ljust (left Width, '.') + str(v).r just (right Width))
picnic Items = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
print Picnic(picnic Items, 12, 5)
print Picnic(picnic Items, 20, 6)

OUTPUT:
---PICNIC ITEMS--
sandwiches.. 4
apples .........12
cups ........... 4
cookies ..... 8000
-------PICNIC ITEMS-------
sandwiches............... 4
apples .................. 12
cups .................... 4
cookies .............. 8000

1.14 Removing Whitespace with strip(), rstrip(), and lstrip()


• Sometimes you may want to strip off whitespace characters (space, tab, and newline)
from the left side, right side, or both sides of a string.
• The strip() string method will return a new string without any whitespace characters
at the beginning or end.
• The lstrip() and rstrip() methods will remove whitespace characters from the left and
right ends, respectively

Output:

>>> spam = ' Hello World '

>>> spam.strip()
'Hello World'

>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()

10
Introduction to Python Programming - 22PLC105B/205B

' Hello World'


NOTE:

• Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital
S from the ends of the string stored in spam.
• The order of the characters in the string passed to strip() does not matter: strip('ampS')
will do the same thing as strip('mapS') or strip('Spam').
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'

>>> spam.strip('ampS')

'BaconSpamEggs‘
• Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital
S from the ends of the string stored in spam

1.15 Copying and Pasting Strings with the pyperclip Module


• The pyperclip module has copy() and paste() functions that can send text to and
receive text from your computer’s clipboard.
• Sending the output of your program to the clipboard will make it easy to paste it to
an email, word processor, or some other software.

Example:

NOTE:
• Pyperclip does not come with Python.
• To install it, follow the directions for installing third-party modules in Appendix A.

• After installing the pyperclip module, enter the following into the interactive shell:
>>> import pyperclip
>>> pyperclip.copy('Hello world!')
>>> pyperclip.paste()
'Hello world!’
1.16 Project: Password locker
#! python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}

import sys, pyperclip


if len(sys.argv) < 2:

11
Introduction to Python Programming - 22PLC105B/205B

print('Usage: py pw.py [account] - copy account password')


sys.exit()

account = sys.argv[1] # first command line arg is the account name


if account in PASSWORDS:

pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')

else:
print('There is no account named ' + account)

1.17 Project: Adding Bullets to Wiki Markup


#! python3
# bulletPointAdder.py - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.
import pyperclip
text = pyperclip.paste()
# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)): # loop through all indexes for "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
pyperclip.copy(text)

12
Introduction to Python Programming - 22PLC105B/205B

Chapter 2: Reading and writing files


• Variables are a fine way to store data while your program is running, but if you want
your data to persist even after your program has finished, you need to save it to a file.
Let’s start with how to use Python to create, read, and save files on the hard drive.
• A file has two key properties: a filename (usually written as one word) and a path.
• The path specifies the location of a file on the computer.
• Example: filename - projects.docx
• Path - C:\Users\asweigart\Documents
2.1 Files and File paths
• A file has two key properties: a filename (usually written as one word) and a path.
• The path specifies the location of a file on the computer.
• For example, there is a file on my Windows 7 laptop with the filename projects.docx in
the path C:\Users\asweigart\Documents.
• The part of the filename after the last period is called the file’s extension and tells you
a file’s type.
• project.docx is a Word document, and Users, asweigart, and Documents all refer to
folders (also called directories).
• Folders can contain files and other folders.
• For example, project.docx is in the Documents folder, which is inside the asweigart
folder, which is inside the Users folder.

13
Introduction to Python Programming - 22PLC105B/205B

• The C:\ part of the path is the root folder, which contains all other folders.
• On Windows, the root folder is named C:\ and is also called the C: drive.
• On OS X and Linux, the root folder is / (Forward Slash).
2.1.1 Backslash on Windows and Forward Slash on OS X and Linux

• On Windows, paths are written using backslashes (\) as the separator between folder
names.

• OS X and Linux, however, use the forward slash (/) as their path separator.
• If you want your programs to work on all operating systems, you will have to write
your Python scripts to handle both cases.
2.1.2 OS. path. join()
• If the string values of individual file and folder names are passed in your path,
os.path.join() will return a string with a file path using the correct path separators.

Example:
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
Note:
• I’m running these interactive shell examples on Windows, so os.path .join('usr', 'bin',
'spam') returned 'usr\\bin\\spam'. (Notice that the backslashes are doubled because each
backslash needs to be escaped by another backslash character.)
• If I had called this function on OS X or Linux, the string would have been
'usr/bin/spam'.
Example 2:
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']

>>> for filename in myFiles:


print(os.path.join('C:\\Users\\asweigart',filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv

14
Introduction to Python Programming - 22PLC105B/205B

C:\Users\asweigart\invite.docx

2.1.3 The Current Working Directory

• Every program that runs on your computer has a current working directory, or cwd.
• Any filenames or paths that do not begin with the root folder are assumed to be under
the current working directory.
• You can get the current working directory as a string value with the os.getcwd()
function and change it with os.chdir().
Example:
>>> import os

>>> os.getcwd() #function returns the current working directory as a string value
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
Python will display an error if you try to change to a directory that does not exist.
>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2.1.4 Absolute vs. Relative Paths
• There are two ways to specify a file path.
• An absolute path, which always begins with the root folder.
• A relative path, which is relative to the program’s current working directory
• There are also the dot (.) and dot-dot (..) folders. These are not real folders but special
names that can be used in a path. A single period (“dot”) for a folder name is shorthand
for “this directory.” Two periods (“dot-dot”) means “the parent folder.”

For example: .\spam.txt and spam.txt refer to the same file.

15
Introduction to Python Programming - 22PLC105B/205B

2.1.5 Creating New Folders with os.makedirs()

>>> import os

>>> os.makedirs('C:\\delicious\\walnut\\waffles')

2.2 The os.path Module

• The os.path module contains many helpful functions related to filenames and file
paths.

2.2.1 Handling Absolute and Relative Paths:


• Calling os.path.abspath(path) will return a string of the absolute path of the argument.

Example 1:
This is an easy way to convert a relative path into an absolute one.

>>> os.path.abspath('.')

‘C:\\Users\\Anand\\AppData\\Local\\Programs\\Python\\Python39'
>>> os.path.isabs('.')

16
Introduction to Python Programming - 22PLC105B/205B

False
>>> os.path.isabs(os.path.abspath('.'))

True
Example 2:
Enter the following calls to os.path.relpath() into the interactive shell:
>>> os.path.relpath('C:\\Windows', 'C:\\')

'Windows'
Example 3:
>>> path = 'C:\\Windows\\System32\\calc.exe'
>>> os.path.basename(path)

'calc.exe'
>>> os.path.dirname(path)

'C:\\Windows\\System32‘
Example 4:

• dir name and base name together can be obtained by using os.path.split() to get a tuple
value with these two strings
>>>path1='C:\\Windows\\System32\\calc.exe'

>>>os.path.split(path1)

('C:\\Windows\\System32', 'calc.exe')
Hence os.path.split() is a nice shortcut if you need both values.

Example 5:
• use the split() string method and split on the string in os.sep.
>>> import os
>>> path1='C:\\Windows\\System32\\calc.exe'
>>> path1.split(os.path.sep)

17
Introduction to Python Programming - 22PLC105B/205B

['C:', 'Windows', 'System32', 'calc.exe']

2.2.2 Finding File Sizes and Folder Contents

• Calling os.path.getsize(path) will return the size in bytes of the file in the path
argument.

• Calling os.listdir(path) will return a list of filename strings for each file in the path
argument.
Output:
>>>os.path.getsize('C:\\Windows\\System32\\calc.exe')

26112 → The size of specified path in bytes.


>>>os.listdir(r'E:\SAMPLE')

['HELLO.docx', 'SAMPLE DATA1']

2.2.3 Checking Path Validity

• os. path. exists(path) →


• will return True if the file or folder referred to in the argument exists
• will return False if it does not exist.
• os. path. is file(path) →
• will return True if the path argument exists and is a file
• will return False otherwise.
• os. path. is dir(path) →
• will return True if the path argument exists and is a folder
• will return False otherwise.
Examples:
>>> os.path.exists('C:\\Windows')
True
>>> os.path.exists('C:\\some_made_up_folder')
False
>>> os.path.isdir('C:\\Windows\\System32')
True
>>> os.path.isfile('C:\\Windows\\System32')
False
>>> os.path.isdir('C:\\Windows\\System32\\calc.exe')
False
>>> os.path.isfile('C:\\Windows\\System32\\calc.exe')
True

18
Introduction to Python Programming - 22PLC105B/205B

2.3 The File Reading/Writing Process:

There are three steps to reading or writing files in Python.

1. Call the open() function to return a File object.


2. Call the read() or write() method on the File object.
3. Close the file by calling the close() method on the File object.

Opening Files with the open() Function


• To open a file with the open() function, you pass it a string path indicating the file you
want to open; it can be either an absolute or relative path.
• The open() function returns a File object.
• hellofile=open(r'E:\SAMPLE\IND.docx')

Reading the Contents of Files


>>> helloContent=hellofile.read()

>>> helloContent

Writing to Files

Example 1:
>>>baconFile = open(r'E:\SAMPLE\HI.txt', 'w')
>>> baconFile.write('Hello world!\n')
13 # returns the number of characters written
>>> baconFile.close()
>>> baconFile = open(r'E:\SAMPLE\HELLO.txt', 'w')
>>> baconFile.write('Hello BHASKARA STUDENTS!\n')
25
>>> baconFile.close()
Example 2:
>>> baconFile = open('bacon.txt', 'a')
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> baconFile = open('bacon.txt')
>>> content = baconFile.read()
>>> baconFile.close()
>>> print(content)
Hello world!
Bacon is not a vegetable.

19
Introduction to Python Programming - 22PLC105B/205B

2.4 Saving Variables with the shelve Module


• You can save variables in your Python programs to binary shelf files using the shelve
module.
• The shelve module will let you add Save and Open features to your program.

Example:
>>> import shelve
>>> shelfFile = shelve.open('mydata')

>>> cats = ['Zophie', 'Pooka', 'Simon']


>>> shelfFile['cats'] = cats

>>> shelfFile.close()

Explanation of the program:

• To read and write data using the shelve module, you first import shelve.
• Call shelve.open() and pass it a filename, and then store the returned shelf value in a
variable.
• You can make changes to the shelf value as if it were a dictionary.
• After running the previous code on Windows, you will see three new files in the current
working directory: mydata.bak, mydata.dat, and mydata.dir

2.5 Saving Variables with the p print. P format() Function


• Recall from “Pretty Printing” from module 2 dictonary concept, that the pprint.pprint()
function will “pretty print” the contents of a list or dictionary.
• while the pprint.pformat() function will return this same text as a string instead of
printing it.

Example:
>>> import pprint
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
>>> fileObj = open('myCats.py', 'w')
>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
83
>>> fileObj.close()

Explanation of the program:

• Here, we import pprint to let us use pprint.pformat().

20
Introduction to Python Programming - 22PLC105B/205B

• We have a list of dictionaries, stored in a variable cats.


• To keep the list in cats available even after we close the shell, we use
pprint.pformat() to return it as a string.
• Once we have the data in cats as a string, it’s easy to write the string to a file, which
we’ll call myCats.py
2.6 Project: Generating Random Quiz Files
Write a python program to do the following
• Creates 35 different quizzes.
• Creates 50 multiple-choice questions for each quiz, in random order.
• Provides the correct answer and three random wrong answers for each question,
in random order.
• Writes the quizzes to 35 text files.
• Writes the answer keys to 35 text files.

Solution: This means the code will need to do the following:

• Store the states and their capitals in a dictionary.


• Call open(), write(), and close() for the quiz and answer key text files.
• Use random.shuffle() to randomize the order of the questions and multiple-
choice options.

Programming Solution:
Step 1: Store the Quiz Data in a Dictionary

#! python3

# randomQuizGenerator.py - Creates quizzes with questions and answers in

# random order, along with the answer key.

*1 import random
# The quiz data. Keys are states and values are their capitals.

*2 capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas':


'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford',
'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho':
'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka',
'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis',
'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi':
'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe',
'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus',
'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island':
'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville',
'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia':

21
Introduction to Python Programming - 22PLC105B/205B

'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison',


'Wyoming': 'Cheyenne'}

# Generate 35 quiz files.

*3 for quizNum in range(35):


# TODO: Create the quiz and answer key files.

# TODO: Write out the header for the quiz.

# TODO: Shuffle the order of the states.

# TODO: Loop through all 50 states, making a question for each.

*1 import the random module


*2 The capitals variable contains a dictionary with US states as keys and their capitals as values.
*3 And since you want to create 35 quizzes, the code that actually generates the quiz and answer
key files (marked with TODO comments for now) will go inside a for loop that loops 35 times

Step 2: Create the Quiz File and Shuffle the Question Order

Now it’s time to start filling in those TODOs.

(Add the following lines of code to randomQuizGenerator.py )

#! python3

# randomQuizGenerator.py - Creates quizzes with questions and answers in

# random order, along with the answer key.

--snip—

# Generate 35 quiz files.

for quizNum in range(35):

# Create the quiz and answer key files.

*1quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')


*2answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')

22
Introduction to Python Programming - 22PLC105B/205B

# Write out the header for the quiz.

*3quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))

quizFile.write('\n\n')

# Shuffle the order of the states.

states = list(capitals.keys())

*4random.shuffle(states)

# TODO: Loop through all 50 states, making a question for each.

Explanation of the program:

• The filenames for the quizzes will be capitalsquiz.txt, where is a unique number for the quiz that
comes from quizNum, the for loop’s counter.
• The answer key for capitalsquiz.txt will be stored in a text file named capitalsquiz_answers.txt.
Each time through the loop, the %s placeholder in 'capitalsquiz%s.txt' and
'capitalsquiz_answers%s.txt' will be replaced by (quizNum + 1), so the first quiz and answer key
created will be capitalsquiz1.txt and capitalsquiz_answers1.txt. These files will be created with
calls to the open() function at *1 and *2, with 'w' as the second argument to open them in write
mode.
• *3 The write() statements at w create a quiz header for the student to fill out.
• *4 Finally, a randomized list of US states is created with the help of the random.shuffle() function
Step 3: Create the Answer Options

Now you need to generate the answer options for each question, which will be multiple choice
from A to D.

#! python3

# randomQuizGenerator.py - Creates quizzes with questions and answers in

# random order, along with the answer key.

--snip—

# Loop through all 50 states, making a question for each.

for questionNum in range(50):

# Get right and wrong answers.

*1 correctAnswer = capitals[states[questionNum]]

23
Introduction to Python Programming - 22PLC105B/205B

*2 wrongAnswers = list(capitals.values())

*3 del wrongAnswers[wrongAnswers.index(correctAnswer)]

*4 wrongAnswers = random.sample(wrongAnswers, 3)

*5 answerOptions = wrongAnswers + [correctAnswer]

*6 random.shuffle(answerOptions)

# TODO: Write the question and answer options to the quiz file.

# TODO: Write the answer key to a file

*1 The correct answer is easy to get—it’s stored as a value in the capitals dictionary

*2 The list of possible wrong answers is trickier. You can get it by duplicating all the values in the
capitals dictionary

*3 deleting the correct answer


*4 selecting three random values from this list

*5 The full list of answer options is the combination of these three wrong answers with the correct
answers

*6 Finally, the answers need to be randomized

2.7 Project: Multiclipboard


Refer page no. 191 of Al Sweigart,“Automate the Boring Stuff with Python”,1 stEdition,
No Starch Press, 2015 text book.

24
Introduction to Python Programming - 22PLC105B/205B

VTU QUESTION PAPER QUESTIONS


1. Explain the following string methods with example. (Feb / Mar 2022 – 8M)
i) join()
ii) islower()
iii)strip()
iv)center()
2. If S=’HELLO WORLD’, explain and write the output of the following statements: (Feb
/ Mar 2022 – 6M)
i) S[1:5]
ii) S[:5]
iii) S[3:-1]
iv) S[:]
3. List out all the useful string methods which supports in python. Explain with an
example for each methods. (July/August 2022 – 10M)
4. With example code explain join() and split() string methods. (Jan/Feb 2021 – 6M)
5. Write s program to count the number of occurrences of character in a string.
(July/August 2022 – 7M)
6. How do we specify and handle Absolute Relative path? (July/August 2022 - 8M)
7. Explain the File Reading / Writing process with suitable programs. (July/August 2022
- 6M)
8. Write python program to create a folder PYTHON and under the hierarchy 3 files
file1,file2 and file3. Write the content in file1 as “VTU” and in file 2 as
“UNIVERSITY” and file 3 content should be opening and merge of file1 and file2.
Check out the necessary condition before write file3. (July/August 2022 - 6M)
9. Explain the following file operations in python with suitable examples. (Jan/Feb 2021
- 6M)
i) Copying files and folders
ii) Moving files and folders
iii) Permanently deleting files and folders
10. What is the difference between OS and OS.path modules? Discuss the following four
methods of OS module:
i) chdir()
ii) walk()
iii) listdir()
iv) getcwd()
11. With a code snippet, explain saving variables using the shelve module and PPrint
Pformat() functions. (Jan/Feb 2021 - 6M)

--------------------------ALL THE BEST------------------------------

25

You might also like