Python: variables, numbers and text
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.
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)
9 5 14 3.5 3 1 49
1name = "Salma" 2age = 15 3print("Hello", name) 4print(age + 1)
Hello Salma 16
1a = 6 2print(a / 2) 3print(5 / 3)
3.0 1.6666666666666667
1x = input("Number: ") 2y = int(x) + 1 3print(y)
Number: 4 5
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.