Week 9 · Unit 7.2: Decomposing problems · 3 lessons
1
Text or number?
Computing 7: Unit 7.2, pp. 44–81
GoalTell a string from an integer, and explain why sensor data must be a number.
New words
string · text inside quotation marks; it can contain letters, digits and other charactersinteger · a whole number with no quotation marks, such as 40 or 255data type · the kind of data a value is, such as a string or an integervariable · a named place in a program where a value is stored
Explanation
Every value in a program has a data type. A string is text inside single or double quotation marks. A string can even contain digits: "40" is a string because it has quotation marks. An integer is a whole number written without quotation marks, such as 40. The computer treats the two types differently. Adding two strings joins them, but adding two integers calculates. A micro:bit sensor gives its data as an integer automatically, so it can be compared with a number. A number stored as text cannot be compared in the same way. The colour of text in an editor changes inside quotation marks, which helps you see strings.
Value
Data type
How you can tell
40
integer
no quotation marks, a whole number
"40"
string
quotation marks
"Zoo"
string
quotation marks
255
integer
no quotation marks, a whole number
Worked examples
Python
1print("5" + "3")
2print(5 + 3)
Output
53
8
Adding two strings joins them together. Adding two integers gives their total. The first line prints the text 53, the second prints the number 8.
A micro:bit sensor gives an integer, so the comparison works. The temperature 22 is an integer, so the program can ask whether it is more than 30. The function str() changes the number into a string, so that it can be scrolled as text.
Python
1level = "80"2if level > 50:
3print("big")
Output
TypeError: '>' not supported between instances of 'str' and 'int'
In ordinary Python, comparing text with a number gives an error, because the computer cannot decide whether a string is greater than an integer. The quotation marks around "80" are the problem.
Class activity
Quote detective (no computer). Write ten cards, one value on each: 7, "7", "cat", 1500, "1500", 0, "0", "Hi!", 36, "36". Sort them into an integer pile and a string pile. The quotation marks are the clue. Then play “predict the sum”: your partner picks two cards and you say what happens when they are added, for example 7 + 36 or "7" + "36". Which pairs calculate and which join? If you have a computer or tablet, an adult can help you check your predictions in a Python editor.
Practice
1
Copy the table and write the data type of each value: integer or string.
Value
Data type
18
?
"18"
?
"Pass"
?
1024
?
18 is an integer. "18" is a string. "Pass" is a string. 1024 is an integer.