☰ Year plan · Communication Technology

Remainders, decisions and averages

Week 2 · Unit 1, Lesson 1 Computational Thinking and Problem Solving (2) · 3 lessons
2

if and else: two ways to go

ICT Prep 3 Term 1, Unit 1, Lesson 1: pp. 8–9
GoalRead an if and else program and say which message the screen shows for a given input.
New words
condition · a test that is either true or falseif / else · run one block if the condition is true, otherwise run the other== · tests whether two values are equalindentation · the spaces at the start of a line that show which block it belongs to
Explanation

Now the decision. The program reads a number, tests the condition num % 2 == 0, and shows one message if it is true and another if it is not. Look at the details. The test uses two equal signs, because one = stores a value in a variable and two == ask a question. The lines if ...: and else: end with a colon. The lines under them are indented by four spaces; this tells Python which lines belong to which branch. A line that is not indented, such as the last line below, runs in every case. In the flowchart, the diamond is the decision with a yes arrow and a no arrow. When the user types 7, the remainder is 1, the condition is false, and the screen shows Odd number.

Startread numnum % 2 == 0yesnoEven numberOdd numberEnd
Worked examples
Python
1num = int(input("Enter a number: "))
2if num % 2 == 0:
3    print("Even number")
4else:
5    print("Odd number")
Output
Enter a number: 12
Even number
The user types 12 into the program. The remainder is 0, the condition is true, and the screen shows Even number.
Python
1num = int(input("Enter a number: "))
2if num % 2 == 0:
3    print("Even number")
4else:
5    print("Odd number")
6print("Done")
Output
Enter a number: 7
Odd number
Done
A last line without indentation always runs. Here the user types 7: the else branch shows Odd number, and then Done is shown for every input, because print("Done") belongs to no branch.
Class activity

On paper, change the program so that it says Positive when num > 0 and Not positive otherwise. Draw the flowchart with the diamond, and say what the screen shows for -3, 0 and 8.

Practice
1
The user types 10. What does the program of this lesson show?
2
What is the difference between = and ==?
3
What must the lines if num % 2 == 0 and else end with?
4
Why is the line print("Done") shown for every input?