☰ Year plan · Communication Technology

Algorithms and Python (1)

Week 11 · Chapter 12 Programming (1): algorithms and flowcharts, Python basics: variables, arithmetic, input, loops and branching · 3 lessons
3

Python: choosing and repeating

ICT Secondary 1 Term 1, Chapter 12, Lessons 12-1 to 12-3: pp. 155–167
GoalWrite and trace Python programs that choose with if and repeat with for and while.
New words
condition · a test that is True or False, such as mark >= 70indentation · the spaces at the start of a line that show which lines belong to a blockfor loop · repeats for each value of a counterwhile loop · repeats as long as a condition is True
Explanation

A condition is True or False. Python compares with == (equal), != (not equal), < > <= >=, and joins conditions with and, or, not. Note that == compares, while a single = stores. The if statement runs its block only when the condition is True; elif gives another condition to try; else runs when none was True. The block is shown by indentation: the lines that belong to the if are pushed in by four spaces after the colon. In the first program, mark = 72 fails mark >= 90, passes mark >= 70, so it prints B. A for loop repeats for each value of a counter: range(1, 5) gives 1, 2, 3, 4 (the end value 5 is not included). The second program adds these four numbers into total and prints 10. A while loop repeats as long as its condition is True; it must change something inside, or it never stops. The third program counts down from 3 and then prints Go. Finally, and joins two conditions: age >= 13 and age < 18 is True only if both parts are True, so for age = 15 it prints True.

Python
1mark = 72
2if mark >= 90:
3    print("A")
4elif mark >= 70:
5    print("B")
6else:
7    print("C")
Output
B
Worked examples
Python
1total = 0
2for i in range(1, 5):
3    total = total + i
4print(total)
Output
10
A for loop with a running total. Trace: i = 1 gives total 1; i = 2 gives 3; i = 3 gives 6; i = 4 gives 10. The range stops before 5.
Python
1n = 3
2while n > 0:
3    print(n)
4    n = n - 1
5print("Go")
Output
3
2
1
Go
A while loop that counts down. Each pass prints n and then makes n smaller by 1; when n is 0 the condition n > 0 is False and the loop ends, and the last line runs.
Python
1age = 15
2print(age >= 13 and age < 18)
Output
True
Combining conditions: age >= 13 and age < 18 asks whether a pupil is a teenager under 18. Both parts are True for 15.
Class activity

On paper, trace this program in a table with columns i and total, then write what it prints: total = 0, for i in range(1, 5): total = total + i * 3, then print(total). Then change the program to count down from 5 with a while loop.

Practice
1
With mark = 85, what prints: if mark >= 90 print A, elif mark >= 70 print B, else print C?
2
What numbers does range(1, 4) give?
3
What is the difference between = and ==?
4
Why must a while loop change something inside its block?