Exercises

These exercises check branches, loops, running totals, and boundaries.

Exercise: Branch order

What does this program print?

Output

Select one choice, then check.

Hint

Check the first condition. If it is false, move to the elif.

Solution

score is 72.

The first condition is false:

score >= 90

The second condition is true:

score >= 50

So the program prints:

pass
Exercise: Range boundary

What is the last value printed?

Compute it first, then check your number.

Hint

range(3) starts at 0 and stops before 3.

Solution

range(3) produces:

0, 1, 2

The last printed value is 2.

Exercise: Fix the running total

Edit the code so the output contains total: 12.

Initialize before the loop

Runs locally with Python in your browser.

Ready to run.

Hint

The line total = 0 should run before the loop begins, not inside the loop.

Solution

Move the initialization before the loop:

Output:

total: 12
Exercise: while loop final value

After the loop finishes, what is count?

Compute it first, then check your number.

Hint

Trace count: start at 0, then update while the condition is true.

Solution

Trace the loop:

Stepcount
start0
after first update1
after second update2
after third update3

At 3, the condition count < 3 is false. The final value is 3.

Exercise: Include one through four

Complete the loop so it prints 1, 2, 3, 4.

Choose the stop value

Runs locally with Python in your browser.

Ready to run.

Hint

The stop value is excluded. To print 4, the stop value must be larger than 4.

Solution

Use range(1, 5):

Output:

1
2
3
4

The stop value 5 is excluded.