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
24
Data types in Python
Textbook: pp. 59–61
GoalTells the data types (int, float, str, bool) apart, finds the type of a value with type(), and converts a string read with input() into a number with int().
New words
data type: the form of the data in a variable or constant; it decides how much memory is used and which operations are allowed · ma’lumotlar turiint is a whole number, float is a real number with a decimal point · int va floatstr: a string, text placed in quotes · strbool: a logical type with only two values, True and False · bool
Explanation
Data in a computer is of different kinds: numbers, text, true or false values. So every value has its own type: int is a whole number (15), float is a real number (20.5, the fractional part is written with a dot), str is a string in quotes (“Lola”), bool is a logical value (True or False, with a capital first letter). In Python you do not have to declare a type beforehand: the type of a variable is found from the value it receives, and the type() function shows it. When the type must be changed, int(), float() or str() is used. An important case: input() returns whatever the user types as a string (str); so to add 1 to a typed 15 you must first convert it with int(), otherwise a TypeError appears. Do not forget that "15" in quotes is text, not a number.
Worked examples
Seeing the types with type(): yosh = 15 ⏎ narx = 20.5 ⏎ ism = "Lola" ⏎ ok = True ⏎ print(type(yosh)) ⏎ print(type(narx)) ⏎ print(type(ism)) ⏎ print(type(ok)) The screen shows in turn <class 'int'>, <class 'float'>, <class 'str'>, <class 'bool'>.
Converting the typed string to a number: s = input() ⏎ print(int(s) + 1) If 15 is typed, 16 is printed. Without int(), print(input() + 1) gives a TypeError, because a number cannot be added to a string.
Class activity
“Type sorting”: each group writes a value on 12 cards (7, 7.0, "7", True, -3, "Lola", 0.5, False, "3.14", 100, "", 2.0) and sorts them into the int, float, str, bool boxes.
Practice
1
Name the types of the values 579, "579", 5.79 and False.
int, str, float, bool.
2
What does print(type(3.0)) print on the screen?
<class 'float'>
3
Write a program that reads a whole number and prints it plus 1.
son = int(input()) ⏎ print(son + 1)
4
Why does input() + 1 give an error?
input() returns a string and a number cannot be added to a string; it must first be converted with int().