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 run it to 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

Predict

For both examples, study the code carefully and write down a prediction before you touch the Run button. Your prediction should use the key terms file, read and iteration, and it should say what the program prints, line by line. You can type your prediction straight into the code as a comment, on a line starting with #. Both blocks come with singers.txt, in a tab next to the code.

Only once you have written your prediction should you run the code and compare the result with what you expected.

Example 1

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.

Answer

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.

Example 2

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.

Answer

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.

Help! My code doesn't work!

Make sure that you check for the following things:

  • The file name is a string, in quotes, and ends in .txt.
  • The mode is "r", in quotes, after a comma.
  • The opened file is stored in a variable, and that same variable name is used in the for line and in the .close() line.
  • The for line and the if line both have a colon (:) at the end.
  • .close() is not indented, so it runs once after the loop.
  • Every line still has its newline on the end, so compare line.strip() rather than line.