☰ 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
2

Python: variables, numbers and text

ICT Secondary 1 Term 1, Chapter 12, Lessons 12-1 to 12-3: pp. 155–167
GoalStore values in variables, do arithmetic in Python, and predict the exact output of short programs.
New words
variable · a named box that stores a valueassignment · the = sign, which stores the value on the right in the name on the leftarithmetic operator · a sign such as + - * / // % ** that calculatesinput() · asks the user to type something and gives it back as text
Explanation

Python is a programming language that reads and runs your lines one by one. print shows something on the screen. A variable is a named box: in age = 15 the = sign is assignment, not the “equals” of mathematics: it stores 15 in the box called age. Text goes between straight quotes. Python has these arithmetic operators: + - * for plus, minus and times; / for ordinary division, which always gives a number with a decimal part (6 / 2 gives 3.0, not 3); // for whole-number division (7 // 2 is 3); % for the remainder (7 % 2 is 1); ** for powers (7 ** 2 is 49). The function input always gives back text, even if the user types digits, so we turn it into a number with int() (a whole number) or float() (a number with a decimal part), and str() turns a number into text. Choose names that do not hide built-in tools: use total, not sum. Remember Week 4, where a character and a number were different things: when the user types 5 and the program does x + "1" on the text "5", the plus sign joins two texts and gives 51.

Python
1a = 7
2b = 2
3print(a + b)
4print(a - b)
5print(a * b)
6print(a / b)
7print(a // b)
8print(a % b)
9print(a ** b)
Output
9
5
14
3.5
3
1
49
Worked examples
Python
1name = "Salma"
2age = 15
3print("Hello", name)
4print(age + 1)
Output
Hello Salma
16
A first program. The comma in print puts a space between the items. age + 1 is a calculation, so the second line shows 16.
Python
1a = 6
2print(a / 2)
3print(5 / 3)
Output
3.0
1.6666666666666667
Division gives a decimal number. a / 2 with a = 6 gives 3.0, and 5 / 3 gives a long decimal that the computer cuts at about 16 digits.
Python
1x = input("Number: ")
2y = int(x) + 1
3print(y)
Output
Number: 4
5
input gives text, so int() is needed before adding. The user typed 4 (shown after the prompt).
Class activity

On paper, predict the screen output of: a = 9, b = 4, then print(a // b), print(a % b), print(a / b), print(a ** 2). Write the four lines and say which of them shows a decimal point. Then check each line by working it out again.

Practice
1
What does print(9 // 2) show?
2
What does print(10 % 4) show?
3
With a = 6, what does print(a / 2) show?
4
Why must we write int(input(...)) before adding to what the user typed?