- Primitive data types
- Strong typing
- The immutability of primitive types
- Explicit type conversion
- Floating point numbers
There are different ways to represent data in programs:
- Strings — sets of characters in quotation marks like
"Hello, World!"
- Integers — for example,
7
,-198
, and0
These are two different categories of information — two different types of data. The multiplication operation makes sense for the integers but not for the strings. Multiplying the word mom
by notepad
is pointless.
The data type determines what we can do with the elements of a particular data set. In this lesson, we'll learn about data types and how typing works in Python.
Primitive data types
The programming language recognizes data types, so Python won't let us multiply a string by another string — you can't multiply text by text. You can multiply an integer by another integer. The existence of types and these restrictions in the language protects programs from accidental errors.
Unlike strings, we do not have to wrap numbers in quotes. To print the number 5, all you have to do is write:
print(5) # => 5
The number 5
and the string '5'
are different data types:
- Integers (
1
,34
,-19
etc.) - Rational numbers (
1.3
,1.0
,-14.324
etc.)
Although, the output given by print()
for this data is identical. This division is due to the peculiarities of how computers work. There are other types, which we'll get to know later.
Here is another example, but with a rational number:
print(10.234) # => 10.234
Strings, integers, and rational numbers are primitive data types. They come built-in to the Python language. Some composite types are built-in, but for now, we will only be working with primitive ones. Programmers can also create their data types.
In English, strings in programming are called strings, and lines in text files are called lines. For example, we see a line but no strings in the code above.
Python is strict about data types. Therefore, it will respond with an error to any incompatibility. It is all to do with typing.
Strong typing
We know two different data types: numbers and strings. For example, we could add numbers because addition is an operation for the numbers type.
But what if you add a number to a string? Let us try:
print(1 + '7') # TypeError: unsupported operand type(s)...
Python will not allow you to add the number 1
to the string '7'
because they are different types. Before that, you should either:
- Turn the string into a number
- The number into a string
We will talk about how to do that later.
This pedantic attitude toward type compatibility is called strict typing or strong typing. It is a distinctive feature of Python.
Not all languages can do this. For example, PHP is a language with weak typing. It knows about different types but uses them not in a strict way. PHP tries to transform information when it makes sense. The same applies to JavaScript:
// Elon Musk, eat your heart out
// Number 1 + String 7 = String 17
1 + '7'; // '17'
On the one hand, automatic implicit type conversion does seem convenient. But in practice, this feature causes a lot of errors, which can be hard to find. The code may or may not work sometimes, depending on how lucky you are with automatic conversion. You might not spot it right away and spend much time debugging.
The immutability of primitive types
Imagine that we need to change a character in a string. Here is what will come out of it:
first_name = 'Alexander'
first_name[0] = 'B'
# Error: TypeError: 'str' object does not support item assignment
It happens because of the immutability of primitive types in Python. The language makes it physically impossible to change strings. The immutability of primitive types is essential for many reasons. The key reason is performance.
But we need to change a string sometimes. It is what we have variables for:
first_name = 'Alexander'
first_name = 'Blexander'
print(first_name) # => Blexander
There's a big difference between changing the value of a variable and changing the value itself. In Python, you can't modify primitive types but can change composite types. You can also replace the value of a variable without any problem.
Explicit type conversion
In programming, you'll regularly encounter tasks where one type of data needs to be converted to another, for example, when working with web forms. Form data always comes in text form, even if the value is a number. Here's how we convert it:
# The string becomes an integer
number = int('345')
print(number) # => 345
We pass the value to the int()
function to convert it. The function behaves similarly to arithmetic operations but does some particular things. Here are a few more examples:
value = '0'
# You can enter a variable inside the brackets
converted_value = int(value)
print(converted_value) # => 0
# Or a specific value
converted_value2 = int('10')
print(converted_value2) # => 10
converted_value3 = int(False)
print(converted_value3) # => 0
converted_value4 = int(True)
print(converted_value4) # => 1
# If we convert a floating point number
# The entire fractional part is discarded
converted_value5 = int(3.5)
print(converted_value5) # => 3
Similarly, you can convert data into strings using str()
and into floating point numbers using float()
:
value = str(10)
print(value) # '10'
value2 = str(True)
print(value2) # 'True'
value3 = float(5)
print(value3) # 5.0
Python does some transformations automatically, for example, in operations where we simultaneously use integer and floating-point numbers. Python automatically converts everything to float (floating point numbers):
# Float(3) + 1.2 is executed implicitly
value = 3 + 1.2
print(value) # => 4.2
Floating point numbers
There are different kinds of numbers in mathematics:
- Natural numbers — integers from 1 and up
- Rational numbers — they have a decimal point, such as 0.5
From a computer's perspective, there is a difference between these types of numbers. For example, we easily calculate 0.2 + 0.1. Now let us see what Python has to say about it:
0.2 + 0.1 # 0.30000000000000004
The addition of two rational numbers suddenly resulted in an inaccurate result. Other programming languages will produce the same result. It is due to the limitations of computing power. Unlike numbers themselves, there's a finite amount of memory. An infinite range of numbers would require an unlimited amount of memory.
Rational numbers do not line up in a continuous chain – there are infinitely many numbers between 0.1 and 0.2 How do you store rational numbers, then? There are many articles on the Internet about memory organization in these cases. Moreover, there is a standard that describes how to do it correctly. The vast majority of languages rely on this standard.
Developers need to understand that operations with floating numbers are inaccurate, but this accuracy can be adjusted when working on specific tasks.