In a predict and run task you do not write code from scratch. You start from a small piece of working code, work out what you think it will do before you run it, and then check whether you were right.
Both examples read the same text file, singers.txt. Its eleven lines are:
Kurt
Debbie
Freddie
Karen
Dave
Brittany
Jon
Gladys
John
Gwen
Geddy
For both examples, study the code carefully and write down a prediction before you look at the output. Your prediction should use the key terms file, read and iteration, and it should say what the program prints, line by line.
These examples open a file, and the code blocks on this page cannot do that, so
the output is given in a spoiler under each example instead of a Run button.
Open it only once your prediction is written down. To run the code for real,
use the To sandbox button of the Modify exercise in this chapter: its
sandbox comes with singers.txt.
my_file = open("singers.txt", "r")
for line in my_file:
print(line)
my_file.close()
How many lines of output are there? Look closely at what comes between the names.
Kurt
Debbie
Freddie
Karen
Dave
Brittany
Jon
Gladys
John
Gwen
Geddy
Every name is printed, in the order it appears in the file, and every name is followed by a blank line: 22 lines of output for 11 names.
The loop repeats once for each line of the file. Each line it reads still has
the file’s newline on the end, and print adds a newline of its own, so every
name ends with two of them.
my_file = open("singers.txt", "r")
for line in my_file:
if line == "John":
print("The singer from The Beatles is saved in the file")
my_file.close()
John is the ninth name in the file. Predict what this program prints, and
how many times.
Nothing at all. The program runs without an error and prints no output.
The loop does reach John, but the line it reads is "John\n", with the file’s
newline on the end, and "John\n" is not equal to "John". The condition is
false for every line in the file, so the print never runs.
.strip() fixes it, by taking the newline off before the comparison:
if line.strip() == "John":
With that change the program prints
The singer from The Beatles is saved in the file once.
Make sure that you check for the following things:
.txt."r", in quotes, after a comma.for line and in the .close() line.for line and the if line both have a colon (:) at the end..close() is not indented, so it runs once after the loop.line still has its newline on the end, so compare line.strip()
rather than line.