Exercises

These exercises combine files, paths, imports, and script shape.

Exercise: Read and count

Edit the code so it prints lines: 3.

Count lines in a file

Runs locally with Python in your browser.

Ready to run.

Hint

Inside the second with block, use file.read(). Then use text.splitlines().

Solution

One fix is:

splitlines returns the three text lines without needing to manually handle the newline characters.

Exercise: Write a result file

Edit the code so the printed file contents include tokens: 4.

Write a token summary

Runs locally with Python in your browser.

Ready to run.

Hint

len(tokens) is a number. Convert it with str(...) before joining it into the file text.

Solution

One fix is:

The count is numeric, so it is converted to a string before being written.

Exercise: Use a path object

Which expression creates the path output/summary.txt?

Answer it first, then check.

Hint

Start with Path("output"), then use / to join the filename.

Solution

Use:

Path("output") / "summary.txt"

The / operator joins path parts when the left side is a Path object.

Exercise: Import from math

After this import, what expression computes the square root of 16?

import math

Answer it first, then check.

Hint

Plain import math means the function is reached through the module name.

Solution

Use:

math.sqrt(16)

Because the import was import math, the name sqrt remains inside the math module.

Exercise: Complete the script shape

Edit the code so the program prints words: 3 by calling main.

Call main from the entry point

Runs locally with Python in your browser.

Ready to run.

Hint

Use:

Solution

One fix is:

The functions can be imported without running the script workflow. The workflow runs only when the file is the entry point.