You are on page 1of 4

Introduction to programming - Exercise Sheet 7 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 17.

57

Introduction to programming - Exercise Sheet 7


- Solution
I’ve selected a few exercises for this task from Python Crash Course, Chapter 10.

Task 1 (Python Crash Course, 10-1)


Open a blank file in your text editor and write a few lines summarizing what you’ve learned
about Python so far. Start each line with the phrase “In Python you can….”.

Save the file as learning_python.txt in the same directory as the one where you store
your Python programs.

Write a program that reads the file and prints what you wrote three times. Print the contents
once by reading in the entire file, once by looping over the file object, and once by storing
the lines in a list and then working with them outside the with block (as suggested in the
preparation material).

Solution:

filename = 'learning_python.txt'

# Reading in the entire file


with open(filename) as f:
contents = f.read()
print
print(contents)

# Looping over the lines


with open(filename) as f:
for line in f:
print
print(line.rstrip())

# Storing the lines in a list


with open(filename) as f:
lines = f.readlines()
for line in lines:
print
print(line.rstrip())

Task 2 (Python Crash Course, 10-4)


https://github.itu.dk/pages/ip/2022/exercises/exercise_07_solutions/ Page 1 of 4
Introduction to programming - Exercise Sheet 7 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 17.57

Write a while loop that prompts users for their name. When they enter their name, print a
greeting to the screen and add a line recording their visit in a file called guest_book.txt .
Make sure each entry appears on a new line in the file by opening it in a text editor.

Solution:

print
print("Please enter 'quit' when finished")
with open('guest_book.txt', 'a', encoding=
="utf8") as f:
while True:
name = input("Please write your name: ")
if name == 'quit':
break
f.write(name + "\n")
print
print(f"Greetings {name}, you are now in the guest book")

Task 3 (Python Crash Course, 10-8)


Make two files, cats.txt and dogs.txt . Store at least three names of cats in the first
file and three names of dogs in the second file.

Write a program that tries to read these files and print the contents of the file to the screen.
Wrap your code in a try-except block to catch the FileNotFound error, and print a
friendly message if a file is missing. Move one of the files to a different location on your
system, and make sure the code in the except block is executed properly.

Solution:

filenames = ['cats.txt', 'dogs.txt']

for filename in filenames:


print
print("\nReading file: " + filename)
try
try:
with open(filename) as f:
contents = f.read()
print
print(contents)
except FileNotFoundError:
print
print(" Sorry, I can't find that file.")

Task 4 (Analyzing a file)


The file sales.txt (find it in the zip file next to the exercise sheet) contains every element
sold by a grocery store within the last 24 hours. First, write a program that just prints the

https://github.itu.dk/pages/ip/2022/exercises/exercise_07_solutions/ Page 2 of 4
Introduction to programming - Exercise Sheet 7 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 17.57

content of the file. Next, write a program that prints the item that has been sold most
frequently.

Suggested Approach: Read the file line-by-line and count frequencies using a dictionary, as
earlier in class. Find the item with maximum frequency and return it.

Suggested solution:

sold = {}
with open('sales.txt') as f:
for line in f:
sold.setdefault(line, 0)
sold[line] += 1
print
print(max(sold, key==sold.get))

Task 5 (MadLibs)
Create a Mad Libs program that reads in text files and lets the user add their own text
anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For
example, the text file madlibs1.txt has the following content:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.

The program would find these occurrences and prompt the user to replace them, like so:

Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck

The following text should then be printed:

The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.

https://github.itu.dk/pages/ip/2022/exercises/exercise_07_solutions/ Page 3 of 4
Introduction to programming - Exercise Sheet 7 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 17.57

A solution that does not account for punctuation:

def read(filename):
with open(filename) as file:
words = file.read().split()
for i in range(len(words)):
if words[i].startswith(('ADJECTIVE')):
words[i] = input('Enter an adjective: ')
if words[i].startswith(('NOUN')):
words[i] = input('Enter a noun: ')
if words[i].startswith(('ADVERB')):
words[i] = input('Enter an adverb: ')
if words[i].startswith(('VERB')):
words[i] = input('Enter a verb: ')
return ' '.join(words)

print(read('madlibs1.txt'))

Asvanced solution accounting for punctuation (uses regex):

import re

def read(filename):
regex = re.compile(r"ADJECTIVE|VERB|ADVERB|NOUN")
with open(filename) as file:
words = file.read().split()
for i in range(len(words)):
if regex.match(words[i]):
match = regex.search(words[i]) # create regex object on word
if match.group() in ('ADJECTIVE', 'ADVERB'):
new = input(f'Enter an {match.group().lower()}: ')
else:
new = input(f'Enter a {match.group().lower()}: ')
words[i] = regex.sub(new, words[i], 1)
return ' '.join(words)

print(read('madlibs1.txt'))

https://github.itu.dk/pages/ip/2022/exercises/exercise_07_solutions/ Page 4 of 4

You might also like