hanegreefs.com/Business Information SystemsBIS
Python 2 · unit 5 of 16

If, while and for

Selection with if, elif and else (the Python version of Case), while loops and their infinite-loop trap, for loops over range and over lists, nested loops, break, and the ATM exercise.

Based on: lecture 4 (Python in a nutshell, the musts of Python) and exercise session WPO3 (if, while and for) · About 65 minutes

Selection: if, elif, elseImportant

In Python a block of statements is marked by indentation (four spaces), not by Begin and End. A colon ends the line that opens the block. This is the Python form of If Then Else:

score = int(input("Score out of 100: "))
if score < 60:
    letter = "F"
elif score < 70:
    letter = "D"
elif score < 80:
    letter = "C"
elif score < 90:
    letter = "B"
elif score <= 100:
    letter = "A"
else:
    letter = "invalid, the maximum is 100"
print("Letter grade:", letter)

Python has no separate Case statement: a chain of elif plays that role. The conditions are tested from top to bottom and only the first True branch runs, which is why score < 70 does not need score >= 60. Conditions can be combined with and, or and not, and Python allows chained comparisons such as 0 <= score <= 100.

Common trapUsing a series of separate if statements instead of elif changes the meaning: every if is tested, so a mark of 55 would pass through several branches and the last one wins. And = assigns while == compares.

While loopsImportant

A while loop repeats its block as long as the condition is True, testing before each round. The pseudo code "sum of numbers until 0" becomes:

total = 0
number = int(input("Give number: "))
while number != 0:
    total = total + number
    number = int(input("Give number: "))
print("The sum is", total)

Notice the read before the loop and again at the end of the body. This pattern is the Python form of the While loop of the algorithm lecture. Python has no Repeat Until loop; you imitate it with while True: and a break when the stop condition holds, so the body runs at least once.

Common trapInfinite loop: if nothing inside the body changes the condition, the loop never ends. counter = 1 followed by while counter < 6: print(counter) without counter += 1 runs forever. In the coding lab such a program is stopped after 4 seconds.
Worked example

Counter from 1 to 6

A counter starts at 1 and stops when it reaches 6; then the counter is displayed.

1

Start

counter = 1
2

Loop

while counter < 6: counter += 1 runs 5 times: 2, 3, 4, 5, 6
3

After the loop

the condition 6 < 6 is False
Answer

The program prints 6. With while counter <= 6 it would print 7: always check the last round.

For loops and rangeImportant

A for loop walks through a sequence: the characters of a string, the elements of a list, or the numbers produced by range.

CallNumbers producedRule
range(5)0, 1, 2, 3, 4starts at 0, stops before 5
range(1, 6)1, 2, 3, 4, 5start included, stop excluded
range(2, 11, 2)2, 4, 6, 8, 10third number is the step
range(10, 0, -3)10, 7, 4, 1negative step counts down
range(5, 1)nothingthe loop body never runs
for x in range(1, 4):
    print("year", x)

for city in ["Brussels", "Ghent", "Liege"]:
    print(city.upper())

for letter in "VUB":
    print(letter)

The For loop of the algorithm lecture, For X from E1 to E2 Step E3, becomes for x in range(E1, E2 + 1, E3): add 1 to the stop value, because range stops before it. When you need both the position and the element, use for i in range(len(lst)) or for i, item in enumerate(lst).

Loops can be nested: the inner loop runs completely for every round of the outer loop. Printing a 3 by 2 matrix uses two loops; the total number of inner rounds is 3 × 2 = 6.

Break, continue and flagsNeutral

break leaves the loop at once; continue skips to the next round. A flag is a Boolean variable that remembers whether something happened (for example found = False, set to True inside the loop) and can be used as the loop condition: while not found and attempts < 3. The lecture solutions mostly use flags and conditions rather than break, which keeps the structure close to the algorithm.

The ATM exerciseImportant

The ATM problem appears in the algorithm lecture, the Python lecture and the exam. A customer inserts a card and gets three attempts for the PIN (assume it is 1234); after three wrong codes the card is kept and the transaction stops. After a correct code a menu offers 1 withdraw money, 2 change PIN, 3 check balance, 4 return card; after options 1 to 3 the menu appears again, after 4 the transaction stops.

The cleanest solution splits the problem in two sub-problems: checking the card and code, and the selection menu. Each part is a loop with its own condition.

attempts = 0
ok = False
while not ok and attempts < 3:
    pin = input("Give your PIN code: ")
    attempts += 1
    if pin == "1234":
        ok = True
    else:
        print("Wrong code")
if not ok:
    print("Card kept")
else:
    choice = 0
    while choice != 4:
        choice = int(input("1 withdraw, 2 new PIN, 3 balance, 4 return card: "))
        if choice == 1:
            print("withdraw money")
        elif choice == 2:
            print("new PIN")
        elif choice == 3:
            print("balance")
    print("Card returned")

Test every case: correct at the first, second and third attempt; three wrong codes; and in the menu each option followed by 4. The coding lab exercise f4 checks the PIN part with four different input series.

Key takeaways

  • Blocks are indentation; a colon opens them.
  • elif chains replace Case; the first True branch wins.
  • while tests before the body; change the condition inside or you get an infinite loop.
  • range(a, b, step) stops before b; For X from E1 to E2 is range(E1, E2 + 1).
  • Split a problem like the ATM into sub-problems, each with its own loop.

Loading cards
Question
Click, tap or press space to flip
Answer

Multiple choice (8)

Question 1 · Python 2

How many times does print run? for i in range(2, 12, 3): print(i)

Why: 2, 5, 8, 11.
Question 2 · Python 2

i = 1; while i < 10: i = i * 2. What is i after the loop?

Why: 1, 2, 4, 8, 16: the loop stops when i is 16.
Question 3 · Python 2

score = 75. Which letter does the program above give?

Why: 75 is not below 60 or 70, but it is below 80.
Question 4 · Python 2

Which loop is guaranteed to run its body at least once in Python?

Why: Only while True with an exit inside always runs once; the others can run zero times.
Question 5 · Python 2

Which code prints 1 to 5 each on a line?

Why: range(1, 6) gives 1 to 5.
Question 6 · Python 2

n = 0; while n != 5: n += 2. What happens?

Why: n takes even values only and never equals 5.
Question 7 · Python 2

What does this print? for c in "abc": print(c, end="")

Why: end="" keeps everything on one line without spaces.
Question 8 · Python 2

In the ATM, the customer types 1111, 2222, 1234. What happens?

Why: The third attempt is still allowed and correct.

Exam-style open questions (2)

Open question · Python 2

Translate a For loop

Translate the pseudo code "For X from 3 to 15 Step 4: Write X" into a Python for loop and into a while loop. What does it print?

Show a model answer outline
  • for x in range(3, 16, 4): print(x)
  • x = 3; while x <= 15: print(x); x += 4
  • Output 3, 7, 11, 15.
  • Stop value plus one because range excludes it.
Open question · Python 2

Menu loop

Explain how you make sure the ATM menu reappears after options 1, 2 and 3 but stops after 4, and which tests you would run.

Show a model answer outline
  • Loop while choice != 4, read the choice inside the loop.
  • elif chain for 1, 2, 3; nothing to do for 4 except leave.
  • Initialise choice before the loop with a value other than 4.
  • Tests: each option then 4; an unknown option; 4 at once.

LabCoding lab: conditions and loops

Program exercises receive simulated keyboard input for each test, so input() works as in the exercise sessions. A loop that never ends is stopped after 4 seconds.

LabRange visualiser

The stop value is never included. A step of 0 is not allowed; with a negative step the start must be larger than the stop.