- №6 Присвоение типа переменной / Уроки по Python для начинающих
- int(): пример преобразования
- float(): пример преобразования
- str(): пример преобразования
- Работа с числами в Python
- Целые и числа с плавающей точкой в Python
- Создание int и float чисел
- Арифметические операции над целыми и числами с плавающей точкой
- Сложение
- Вычитание
- Умножение
- Деление
- Деление без остатка
- Остаток от деления
- Возведение в степень
- Комплексные числа
- Python Float: Working With Floating-Point Numbers
- What is a Python float?
- Creating floating point numbers
- Working with Python floats
- Round, floor, and upper
- Comparisons
- The Python float has limited precision
- Solving the limited precision
- Converting floats to other data types
- Get certified with our courses
- Learn more
№6 Присвоение типа переменной / Уроки по Python для начинающих
Порой, в работе с Python вам может понадобиться явно указать тип переменной. Это можно сделать с помощью преобразования. Python — объектно-ориентированный язык программирования, в нем используются классы для определения типов данных, включая простые типы.
Преобразование в Python выполняется с использованием функций-конструкторов:
- int() — создает целочисленное число из числового значения, либо значения с плавающей точкой (округляя его до предыдущего целого числа) или строкового значение (при условии, что данная строка является целым числом)
- float() — так же создает число, но с плавающей точкой из целочисленного значения, значения с плавающей точкой или строкового (при условии, что строка представляет собой число с плавающей точкой или целое число)
- str() — создает строку из многих типов данных, включая строки, целые числа и числа с плавающей точкой.
int(): пример преобразования
x = int(1) # x станет 1 y = int(2.8) # y станет 2 z = int("3") # z станет 3
float(): пример преобразования
x = float(1) # x станет 1.0 y = float(2.8) # y станет 2.8 z = float("3") # z станет 3.0 w = float("4.2") # w станет 4.2
str(): пример преобразования
x = str("s1") # x станет 's1' y = str(2) # y станет '2' z = str(3.0) # z станет '3.0'
Работа с числами в Python
В этом материале рассмотрим работу с числами в Python. Установите последнюю версию этого языка программирования и используйте IDE для работы с кодом, например, Visual Studio Code.
В Python достаточно просто работать с числами, ведь сам язык является простым и одновременно мощным. Он поддерживает всего три числовых типа:
Хотя int и float присутствуют в большинстве других языков программирования, наличие типа комплексных чисел — уникальная особенность Python. Теперь рассмотрим в деталях каждый из типов.
Целые и числа с плавающей точкой в Python
В программирование целые числа — это те, что лишены плавающей точкой, например, 1, 10, -1, 0 и так далее. Числа с плавающей точкой — это, например, 1.0, 6.1 и так далее.
Создание int и float чисел
Для создания целого числа нужно присвоить соответствующее значение переменной. Возьмем в качестве примера следующий код:
Здесь мы присваиваем значение 25 переменной var1 . Важно не использовать одинарные или двойные кавычки при создании чисел, поскольку они отвечают за представление строк. Рассмотрим следующий код.
В этих случаях данные представлены как строки, поэтому не могут быть обработаны так, как требуется. Для создания числа с плавающей точкой, типа float , нужно аналогичным образом присвоить значение переменной.
Здесь также не стоит использовать кавычки.
Проверить тип данных переменной можно с помощью встроенной функции type() . Можете проверить результат выполнения, скопировав этот код в свою IDE.
var1 = 1 # создание int
var2 = 1.10 # создание float
var3 = "1.10" # создание строки
print(type(var1))
print(type(var2))
print(type(var3))В Python также можно создавать крупные числа, но в таком случае нельзя использовать запятые.
# создание 1,000,000
var1 = 1,000,000 # неправильноЕсли попытаться запустить этот код, то интерпретатор Python вернет ошибку. Для разделения значений целого числа используется нижнее подчеркивание. Вот пример корректного объявления.
# создание 1,000,000
var1 = 1_000_000 # правильно
print(var1)Значение выведем с помощью функции print :
Арифметические операции над целыми и числами с плавающей точкой
Используем такие арифметические операции, как сложение и вычитание, на числах. Для запуска этого кода откройте оболочку Python, введите python или python3 . Терминал должен выглядеть следующим образом:
Сложение
В Python сложение выполняется с помощью оператора + . В терминале Python выполните следующее.
Результатом будет сумма двух чисел, которая выведется в терминале.
Теперь запустим такой код.
В нем было выполнено сложение целого и числа с плавающей точкой. Можно обратить внимание на то, что результатом также является число с плавающей точкой. Таким образом сложение двух целых чисел дает целое число, но если хотя бы один из операндов является числом с плавающей точкой, то и результат станет такого же типа.
Вычитание
В Python для операции вычитания используется оператор -. Рассмотрим примеры.
>>> 3 - 1 2 >>> 1 - 5 -4 >>> 3.0 - 4.0 -1.0 >>> 3 - 1.0 2.0
Положительные числа получаются в случае вычитания маленького числа из более крупного. Если же из маленького наоборот вычесть большое, то результатом будет отрицательно число. По аналогии с операцией сложения при вычитании если один из операндов является числом с плавающей точкой, то и весь результат будет такого типа.
Умножение
Для умножения в Python применяется оператор * .
>>> 8 * 2 16 >>> 8.0 * 2 16.0 >>> 8.0 * 2.0 16.0
Если перемножить два целых числа, то результатом будет целое число. Если же использовать число с плавающей точкой, то результатом будет также число с плавающей точкой.
Деление
В Python деление выполняется с помощью оператора / .
>>> 3 / 1 3.0 >>> 4 / 2 2.0 >>> 3 / 2 1.5
В отличие от трех предыдущих операций при делении результатом всегда будет число с плавающей точкой. Также нужно помнить о том, что на 0 делить нельзя, иначе Python вернет ошибку ZeroDivisionError . Вот пример такого поведения.
>>> 1 / 0 Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero
Деление без остатка
При обычном делении с использованием оператора / результатом будет точное число с плавающей точкой. Но иногда достаточно получить лишь целую часть операции. Для этого есть операции интегрального деления. Стоит рассмотреть ее на примере.
Результатом такой операции становится частное. Остаток же можно получить с помощью модуля, о котором речь пойдет дальше.
Остаток от деления
Для получения остатка деления двух чисел используется оператор деления по модулю % .
>>> 5 % 2 1 >>> 4 % 2 0 >>> 3 % 2 1 >>> 5 % 3 2
На этих примерах видно, как это работает.
Возведение в степень
Число можно возвести в степень с помощью оператора ** .
Комплексные числа
Комплексные числа — это числа, которые включают мнимую часть. Python поддерживает их «из коробки». Их можно запросто создавать и использовать. Пример:
Python Float: Working With Floating-Point Numbers
Besides integers, consisting of whole numbers without fractions, Python also offers us the float type. Perhaps you’ve already seen floats without realizing it. After all, when you divide two integers in Python, the result of that division is often of type float.
In this article, I’ll explain what floats are and how to use them. We’ll also look at an important limitation of floats that you need to be aware of.
What is a Python float?
a Python float is a numerical data type that represents a floating-point number. A floating-point number is a number with a decimal point or exponent notation, indicating that a number is a certain number of digits before and after the decimal point or exponent. For example, the number 1.23 is a floating-point number with one digit before the decimal point and two digits after the decimal point.
Creating floating point numbers
There are multiple ways to create floating-point numbers in Python. Most of the time, you will simply enter the number as-is:
# You can simply enter the number f = 1.45But you may want to convert a number or a string to a float using the float() function. The variable f will become 2.0 in all cases below:
# f will become 2.0 in all cases below f = float(2.0) f = float(2) f = float("2")You can also use scientific notation:
Working with Python floats
Working with floats is not much different from working with integers. You can do the usual addition, subtraction, multiplication, and division.
x = 1.45 y = 4.51 # Add x and y z = x + y # Subtract x and y z = x - y # Multiply x and y z = x * y # Divide x and y z = x / yRound, floor, and upper
With floats, we often need to round numbers. For this, Python has the round function. The round function accepts two arguments: the number itself and an optional precision (the number of decimals). The default for this last number is 0, meaning that it will round to whole integers. Some examples:
>>> f = 1.4567 >>> round(f) 1 >>> round(f, 2) 1.46 >>> f = 1.54 >>> round(f) 2 >>> round(f, 1) 1.5While round is available without importing, we need to do an import from the math library to floor and ceil a number.
The floor function rounds a float down to the nearest integer while the ceil function rounds a float up to the nearest integer. Here’s an example of how you can import and use these functions:
from math import floor, ceil # Round 1.23 down to the nearest integer x = floor(1.23) # x will be 1 # Round 1.23 up to the nearest integer y = ceil(1.23) # y will be 2Comparisons
Just like other types of numbers, floats can be compared using comparison operators such as == , != , > , < , >= , and
x = 1.23 y = 4.56 if x == y: print("x and y are equal") else: print("x and y are not equal")The Python float has limited precision
Let’s do a little experiment. For extra dramatic effect, try this for yourself first:
>>> 0.3 + 0.1 0.4 >>> 0.1 + 3.8 3.9 >>> 0.1 + 0.2 # What is the output of this last statement?Did you expect the output to be 0.3 like any normal person would? I don’t blame you, but you’re wrong! The output is actually 0.30000000000000004 . As absurd as this might seem, there’s an explanation.
First of all, some fractional numbers are endless. E.g., when you divide 1 by 3, you can round the result to 0.33, 0.333333333, or 0.333333333333333333. No matter what precision you choose, there will always be more 3’s. Since there’s a limited number of bits to store a float number, many numbers are a best-effort approximation. So floating-point numbers have limited precision because they are stored in a finite amount of memory, sometimes leading to unexpected results when performing arithmetic operations on floating-point numbers.
Solving the limited precision
The limited precision of floats is a fundamental property of how floats are represented in computer memory. Therefore, it is not possible to completely eliminate the issue of limited precision when working with floats.
However, there are a few ways that you can mitigate the effects of limited precision when working with floats in Python:
- Use the decimal module: The decimal module in the Python standard library provides support for decimal floating-point arithmetic. This allows you to work with decimal numbers that have fixed precision, which can be useful for applications that require more precise calculations than what is possible with regular floats. The downside: floats are much faster than using the decimal pacakge.
- Use NumPy: The numpy module is a popular scientific computing library for Python that supports working with arrays of numbers. The numpy module provides a data type called numpy.float128 that allows you to work with higher-precision floating-point numbers than regular floats.
- Round your floats: As mentioned earlier, you can use the round function to round a float to a specified number of decimal places. Limiting the number of decimal places used in your calculations can help reduce the strange effects of limited precision, but this method makes your calculations even more imprecise.
Converting floats to other data types
You can convert a float to other data types, such as int or str , using the built-in functions int() and str() . For example, the following code converts the float 1.23 to an integer and a string:
# Convert float to integer my_int = int(1.22) # my_int will be 1 # Convert float to string my_str = str(2.23) # my_str will be "2.23"Get certified with our courses
Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.
Learn more
This article is part of my Python tutorial. You can head over to the start of the tutorial here. You can navigate this tutorial using the buttons at the top and bottom of the articles. To get an overview of all articles in the tutorial, please use the fold-out menu at the top.
If you liked this article, you might also like to read the following articles: