0 characters
7. Data types in Python
Summary- In programming, a data type represents a set of values and operations that can be performed on it.
- Python has standard data types: numbers, strings, lists, dictionaries, tuples, sets, and a boolean data type.
- Python refers to languages with implicit strong dynamic typing.
- The data model includes objects, data, and relationships between them.
- The assignment operation in Python creates a reference between a variable and an object that has a type, identifier, and value.
- Numbers in Python can perform various mathematical operations and transformations.
- Strings in Python are an immutable data type and can be added, multiplied by a number and indexed.
- Boolean values are the most primitive data type in Python and can take two values: true or false.
- The undefined None data type can be assigned to a separate data type and can reset the variable to its original state.
Introduction
In the previous lesson You may have been hit by a new flood of information. Let's start by analyzing the concept of "data type" in programming and optionally in Python. A data type is a set of values and operations that can be performed on them. We won't go any further. What are the standard data types in Python?
Python has numbers, strings, lists, dictionaries, tuples, sets, and a boolean data type. We will consider lists, dictionaries, tuples and sets Introduction to the section «Data structures in Python», there will be several lessons for each of them. So, data types in Python can be classified as follows:
- changeable (sets, lists, dictionaries);
- immutable (tuples, strings, numbers);
- ordered (lists, strings, tuples, dictionaries);
- disordered (sets).
An important feature of the Python language is its typing. Python refers to languages with implicit strong dynamic typing. What does this mean? Implicit typing: when declaring a variable, you do not need to specify the specific data type to which it belongs, as, for example, in C++:
int a = 10;
In Python, declaring a variable is very simple:
a = 10
Dynamic typing means that error detection will be performed at the program execution stage. In languages with static typing, error detection is performed at the compilation stage. For example, in Python, it is possible to assign an object of one data type to one variable first, and then another. In the example below, we assign a string to the variable a
first, then a number:
a = "Hello"
a = 1
Strong (or strict) typing means that the Python language does not allow mixing data types. If you set a variable as a number, you will not be able to add it to a string:
a = 10
print('Ten = ' + a)
This increases the reliability of the code, since you need to explicitly convert a number to a string:
a = 10
print('Ten = ' + str(a))
The data model
Before moving on to specific data types, let's take a cursory look at what a data model is, how objects are created in memory, and how the assignment operation (=
) works.
To declare a variable in Python, you must specify its name, put an assignment sign (=
) and write the value that will be stored in the variable. Example:
a = 10
We assigned the number ten to the variable named a
. The integer ten is an object, like everything in Python: numbers, strings, lists, etc. An object is an abstraction of data. Data is not only objects, but also the relationships between them. An object consists of three parts: type, identifier and value.
What happens when initializing a variable at the interpreter level? An integer object 10
is created, which is stored somewhere in memory. This object has an identifier, a value of 10
and an integer type. Using the assignment operator (=
), a reference is created between the variable a
and the object 10
, of integer type.
The variable name must not match the Python keywords. To check this, you can use the iskeyword()
method from the keyword
module.
import keyword
keyword.iskeyword("for") # => True
Consider the following example to better understand how assignment works in Python:
a = 5
b = 10
print(id(a)) # => 140732499849616
print(id(b)) # => 140732499849776
a = b
print(id(a)) # => 140732499849776
We use the id
function to determine the identifier referenced by the variable. Don't get attached to specific numbers, they will be different for you. Note that after the assignment, the identifier referenced by the variable has changed. We will remember this later when we talk about copying lists. And let's also remember when we get acquainted with the arguments and parameters of functions in Python.
To find out the type of a variable, use the function type()
:
a = 5
print(type(a)) # => <class 'int'>
Now you are ready to parse specific data types in Python.
Numbers
You can perform various mathematical operations with numbers in Python:
a = 5 + 6
b = (4 * 6) + 12
c = 2 ** 16 # exponentiation
d = 3 / 2 # => 1.5
Using the round()
function, you can round the result to a certain sign:
d = 10 / 6
print(round(d, 5)) # => 1.66667
The remainder of the division can be found using the %
operator:
d = 10 % 6
d # => 4
The numbers can be compared with each other:
a == b
– checks if both operands are equal and returns true if so;a != b
– checks if both operands are equal and returns true if they are different;a > b
– returns true if the left operand (a) is greater than the right operand (b);a < b
– returns true if the left operand (a) is less than the right operand (b);a >= b
– returns true if the left operand (a) is greater than or equal to the right operand (b);a <= b
– returns true if the left operand (a) is less than or equal to the right operand (b).
print(10 > 5) # => True
# etc…
Since the language is strongly typed, it is often necessary to convert a string to a number. This can be done using the int()
function:
a = '100'
b = int(a)
print(type(a)) # => <class 'str'>
print(type(b)) # => <class 'int'>
To get the binary or hexadecimal value of a number, the bin()
and hex()
functions are used`, respectively. By the way, the result is a string:
a = 16
print(bin(a)) # => 0b10000
print(hex(a)) # => 0x10
You can also combine operations and functions as you like:
a = bin(int('100') + 20)
print(a) # => 0b1111000
For more complex mathematical operations, there is a math
module, which we will talk about later. For example, let's find the root of the number ten:
import math
print(math.sqrt(10))
To summarize. Various mathematical operations and transformations can be performed with numbers. Python has integers, floating point numbers, and complex numbers.
Strings
Strings in Python are a sequence of characters framed by quotation marks. Strings are an immutable data type. Strings can be framed with both single and double quotes. You can also assign multiple lines to a variable, for which the text is limited to three consecutive quotes:
a = 'Hello'
a = "Hello"
a = """
Several
Lines
"""
The strings can be combined (concatenated) into one. We will talk about concatenation later in the topic about lists.
a = 'Hello '
b = "World"
print(a + b) # => Hello World
Strings can be multiplied by a number. The number indicates the number of times the string will be repeated.
Strings in Python are an ordered data type, just like lists, so individual characters can be accessed by index. Indexing starts from scratch:
a = 'Hello'
print(a[0]) # => H
You can also refer to the last character if you use a negative value. About reverse indexing let's also remember in the topic about lists.
a = 'Hello'
print(a[-1]) # => o
In Python, it is possible to make a line slice (we will talk about slices more details later):
a = 'Hello'
print(a[0:3]) # => Hel
print(a[1:]) # => ello
print(a[-3:]) # => llo
print(a[::2]) # => Hlo
To count the number of characters in a string (or the number of items in a list), use the len()
function:
a = 'Hello'
print(len(a)) # => 5
The concepts of "function" and "method" have been heard more than once. What's the difference? As a rule, the method is bound to an object of a specific type, and the function is more universal and can be applied to objects of different types. Learn more about the functions of you will find out later.
You will learn about formatting strings in next lesson.
Boolean values
This is the most primitive data type in Python, and in any programming language, which can take two values: true (True
) or false (False
). A small caveat, in Python, not only True
and False
are considered false and true values.
The true values in Python include:
- any number is not equal to zero;
- any non-empty string;
- any non-empty object.
False values in Python include:
- zero (
0
); None
;- an empty line;
- an empty object.
To check whether the value of an object is false or true, use the bool()
function:
list_a = [1, 2, 3]
list_b = []
num_a = 0
str_a = ''
print(bool(list_a)) # => True
print(bool(list_b)) # => False
print(bool(num_a)) # => False
print(bool(str_a)) # => False
You will get to know the logical data type even more closely in the lesson on the conditional construction if/else
.
Undefined data type None
The undefined value None
can be attributed to a separate data type. If you assign the value None
to a variable, it will be reset to its original state.
Lists, dictionaries, tuples and sets
This is a very extensive and important topic, which we will talk about later and in more detail, starting from this lesson.
A list is a sequence of comma–separated elements and framed by square brackets, for example:
a = [1, 2, 3, 4, 5]
b = ["Hello", 1, 2, a]
By the way, this form of creating lists (and not only) is called literal. A literal in programming is an expression that creates an object.
Dictionary is an ordered data type in which values are stored as a key/value. In other programming languages, it can be called an associative array. It looks like this:
c = {
1: "One",
2: "Two"
}
Note that the dictionary in Python is set in curly brackets.
Tuple is the same list, but only immutable. It looks like this:
d = (1, 2, 3)
That is, the elements in the tuple are placed in parentheses.
Set – an unordered list of unique elements. For example:
e = {1, 1, 1, 2, 2, 3}
e # => {1, 2, 3}
The elements of the set are written in curly brackets separated by commas.
In this lesson, we figured out what a data model is, what the main data types are in Python, and also began to get acquainted with lists, dictionaries, tuples and sets.
In the next lesson, we will look in detail at formatting strings in Python. Let's get acquainted with the methods of formatting strings and choose a convenient one for ourselves.
Test task
Subscribe to our Telegram channel!
News, useful material,
programming and InfoSec