Division in Python

by Alex
Division in Python

Python is a popular high-level programming language. It has a large set of tools, has dynamic typing, and is used to solve all kinds of problems. Division in Python is divided into three types: normal, integer and taking the remainder. The programmer doesn’t need to worry about operand types; Python determines them on its own and converts the result to the desired type. We will learn how to do this in this article.

Division operator

Division in Python is denoted by the slash “/”. Notably, the result in the console is always converted to the “float” type, even if both operands are of integer type, as evidenced by the “.0” in the resulting value. This appeared in version 3 of Python, previously the result of dividing integers was only an integer, to get a fractional result, programmers explicitly specified one of the operands as the “float” type, otherwise the fractional part was simply discarded. It is important to understand that division in Python, like other operations, is slower than in lower-level programming languages. This is due to the high level of automation and abstraction; because of dynamic typing, the interpreter is forced to cast numbers to the fractional “float” type, which requires more memory. Division in the human representation is different from its representation in the computer. A computer is designed so that all arithmetic operations can only be performed through addition. This means that the fastest operations are addition, then subtraction, where it is necessary to change the sign of the operands, and multiplication, where the number is added many times. Division takes the longest, because in addition to the repeated addition operation, it is also necessary to change the sign of the operands, which requires more memory and action. Examples:

print(int(1) / int(2))
print(5 / 5)
print(1 / 3)

0.5
1.0
0.3333333333333333

From the example, you can see that even though in all cases the operation was between integers, the result of division in Python 3 is a real number. In the first case, we even specifically used a conversion to the int type.

Additionally, I’d like to point out that if float data type accuracy is not enough, you can use the decimal library. In particular, we used it when writing our “calculator” program in a separate article.

Division without the remainder

To do integer division in Python, you can use integer division. In this case, the result will be an integer, without a remainder. Integer division in Python is indicated by two slashes “//”. Unlike other programming languages, Python allows the result of integer division to be either an integer (int) or a fractional (float) number. In both cases the fractional part is discarded and you get a number with the ending “.0”. Examples of finding an integer part of a division:

print(5 // 2)
print(0 // 2)
print(1234 // 5.0)

2
0
246.0

In the first two cases division was done between integers. Therefore, the result was an integer. In the third example, one of the numbers is a real number. In this case, the result is also a real number (float type) with 0 after the decimal point.

The remainder

To get the remainder of a division in Python 3, you use the operation denoted by the percent symbol “%”. The remainder is the remainder after integer division. The operation of taking the remainder is used to solve various kinds of problems. Examples:

print(10 % 3)
print(5 % 10)
print(5 % 0.25)

1
5
0.0

Determining the remainder of division is very often used in programs to find, say, even numbers. Or, for example, if data processing is done in a loop, and you want to output a message to the console about the processing progress not every time, but at every 10th iteration. Here is an example of how to output the even integers from the list to the console:

example_list = [3, 7, 2, 8, 1, 12]
for value in example_list:
    if value % 2 == 0:
        print(value)

2
8
12

The problem with floating point numbers

The way computers are set up, they understand only two numbers at the hardware level: one and zero. Because of this, division and other operations with fractions often cause problems. For example, 1/10 in binary is an incorrect infinity fraction. It cannot be written in its entirety, so it has to be rounded, and the choice of value when rounding is limited to zero and one. What can we say about division, if errors occur in the addition operation as well. If you add “0.1” to itself fourteen times, you get 1.400…01. Where did this unit come from? It came from converting a number from binary to decimal.

a = 0.1
for i in range(13):
    a += 0.1
print(a)

1.4000000000000001

More technically complex division results in such inaccuracies much more often. Usually Python rounds the result so that the user doesn’t notice the problem, but if the number is long enough, the problem will show up.

Division of complex numbers

Complex numbers are numbers of the form “a + b-i”. They occupy the highest level in the hierarchy of numbers, arithmetic operations on them are quite different from operations on prime numbers. Dividing a complex number by a regular number changes only the length of the vector radius, but not its direction. Example:

print((5 + 8j) / 2)

(2.5+4j)

Abbreviated Division Operations

To make life easier for programmers, the developers of Python have included “abbreviated operations” in the language. They are used if you want to perform an operation on a variable, and write the result to the same variable. What is written in long form can be written in shorter form according to the following rules:

Full form Short form
Division a = a / b a /= b
Integer part a = a // b a //=b
Remainder a = a % b a %= b

Here is an example:

a = 245
a %= 17
print(a)

7

Division by zero

If we try to do division by 0 in Python, we get a ZeroDivisionError exception. The exception should be handled, it can be done like this:

try:
    print(24 / 0)
except Exception as e:
    print(e)

division by zero

But in this case we handle all the exceptions. It is often not quite correct to do so. We know that division by 0 is possible in our code, so to catch exactly this error we should replace except Exception as e: with except ZeroDivisionError as e:. But you can also check before executing an operation that the divisor is not 0. For example, like this:

a = 14
b = None
if a == 0:
    print('the divisor is zero!')
else:
    b = 345/a
    print('Operation complete, result = ' + str(b))

Operation complete, result = 24.642857142857142

Related Posts

LEAVE A COMMENT