Lessons 24–25 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
25
Practical lesson: data types
Textbook: p. 61
GoalIn the practical lesson, finds variable types with type(), converts typed data with int() and float(), and writes simple calculation programs using numbers typed by the user.
New words
type(): the function that returns the data type of a value · type()int(): converts a value to a whole number · int()float(): converts a value to a real number · float()input(): reads what the user types; the result is a string · input()
Explanation
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.
Worked examples
A cube-shaped box: a = int(input()) ⏎ V = a * a * a ⏎ S = 6 * a * a ⏎ print(V) ⏎ print(S) If the edge 3 is typed, the volume is 27 and the surface area 54.
Average mark: a = float(input()) ⏎ b = float(input()) ⏎ c = float(input()) ⏎ print((a + b + c) / 3) If 4, 5 and 4.5 are typed, 4.5 is printed. Types: a = 12 ⏎ b = "12" ⏎ c = 12.0 ⏎ print(type(a), type(b), type(c)) shows the int, str and float types.
Class activity
“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.
Practice
1
If a trapezium has bases 6 and 4 and height 3, what is its area by the formula S = (a + b) * h / 2?
15
2
A square garden has a side of 9 m. How many metres of fence are needed to go around it?
36
3
If x = 9 and y = 4, what is the type of x / y?
float
4
Why may float() be better than int() for a price?
A price may be fractional (for example 12.5); int() gives an error when converting a fractional string.