☰ Year plan · Communication Technology

Formulas, comparisons and loops

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

Turning a formula into code: area

ICT Prep 3 Term 1, Unit 1, Lesson 1: pp. 10–17
GoalTurn a known formula into Python lines and use * and brackets correctly.
New words
formula · a rule that gives a result from some valuesarea · the amount of surface a shape coversperimeter · the distance all the way around a shape* · the Python sign for multiplication
Explanation

If you know a formula, writing the program is easy. The area of a rectangle is length times width. The program has the same three parts as before: read two numbers, calculate, show. In Python the times sign is *, so the formula becomes area = length * width. When the user types 6 and 4, the screen shows 24. A formula with more than one operation needs care. The perimeter of a rectangle is two times the sum of the length and the width. If we forget the brackets and write 2 * length + width, Python multiplies first and gives the wrong answer, as in Week 2. So we write 2 * (length + width). Formulas are everywhere: a price list is also a formula, cost = price * count.

Python
1length = int(input("Length in cm: "))
2width = int(input("Width in cm: "))
3area = length * width
4print(area)
Output
Length in cm: 6
Width in cm: 4
24
Worked examples
Python
1length = int(input("Length in cm: "))
2width = int(input("Width in cm: "))
3perimeter = 2 * (length + width)
4print(perimeter)
Output
Length in cm: 6
Width in cm: 4
20
Here is the perimeter program. With 6 and 4 the sum in the brackets is 10, and two times 10 is 20.
Python
1price = 12
2count = 5
3cost = price * count
4print(cost)
Output
60
Omar’s canteen sells juice for 12 each. A formula for the cost of 5 juices is price times count. The price and the count are fixed in the first two lines, so no typing is needed.
Class activity

Write the formula and the Python lines for the area of a square whose side is typed by the user. Then do the same for the cost of a number of pencils at a price you choose. Work out the answer for one test by hand.

Practice
1
The user types length 9 and width 3. What does the area program show?
2
What does the perimeter program show for 9 and 3?
3
Why does the perimeter formula need brackets?
4
Which sign multiplies in Python?