Practical lesson: data types
This practical lesson does three jobs: finding a type, converting a typed number to the chosen type, and calculating. int() is used for a whole number that arrives as a string and float() for a number with a fractional part; int() is handy when the edge of a box is a whole number of centimetres, and float() when a mark or a price may be fractional. The signs + (addition), * (multiplication) and / (division) are used in the calculation; you will learn about them in detail in the next lesson. Note that the result of / is always a float: 150 / 60 gives 2.5 and 6 / 3 gives 2.0. First work out the result in your notebook yourself, and then compare it with the answer of the program; if they differ, the usual cause is a wrong type or a wrongly written variable name.
For a school sports day a pupil collected running times and worked out the average. Numbers written as text cannot be added, so the pupil converted them to numbers first.
Spreadsheet users, researchers and programmers convert text data into numbers before calculating.
Write the steps for finding the average of three marks that were typed in as text: what must be converted first and with which function, then what is calculated.
1a = int(input()) 2V = a * a * a 3S = 6 * a * a 4print(V) 5print(S)
27 54
1a = float(input()) 2b = float(input()) 3c = float(input()) 4print((a + b + c) / 3) 5 6a = 12 7b = "12" 8c = 12.0 9print(type(a), type(b), type(c))
4.5 <class 'int'> <class 'str'> <class 'float'>
“Predict the program”: the group feeds the two programs above (box and average mark) numbers they thought of, first predicts the answer in a notebook, and then a partner runs the program to check.