Python is a high-level, interpreted programming language that is widely used in various applications, such as web development, data analysis, artificial intelligence, and scientific computing. One of the built-in functions in Python is the mod function, which is used to calculate the remainder of a division operation. In this article, we will discuss the mod function in Python, its syntax, and how it works. We will also provide some examples to illustrate its usage.
What is Python Mod() Function?
The mod function in Python is used to calculate the remainder of a division operation between two numbers. The remainder is the amount left over after the division is performed. For example, the remainder of the division operation 10/3 is 1, since 10 divided by 3 equals 3 with a remainder of 1. The mod function returns the remainder of a division operation as a single value.
Syntax of the Python Mod Function
The syntax of the mod function in Python is as follows:
result = x % y
where x and y are the two numbers being divided, and the result is the remainder of the division operation.
Return Type of the Python Mod Function
The Python Mod Function returns the remainder of the parameters passed.
How does the Python Mod Function Work?
The mod function in Python works by performing the division operation between two numbers and returning the remainder. If the division operation results in a whole number, then the remainder is zero. For example, the mod function for 6 % 3 would return 0, since 6 divided by 3 is 2 with no remainder.
If the division operation results in a decimal or fractional value, then the mod function returns the decimal or fractional part as the remainder. For example, the mod function for 10 % 3 would return 1, since 10 divided by 3 equals 3 with a remainder of 1, which is the decimal part.
The mod function also works with negative numbers. In this case, the result of the mod function will have the same sign as the divisor (the second argument). For example, the mod function for -10 % 3 would return 2, since -10 divided by 3 equals -3 with a remainder of -1, and the remainder with the same sign as the divisor is 2.
Examples of the Python Mod Function
Let’s look at some examples of using the mod function in Python.
Example 1: Python Mod function with positive numbers
When both the dividend (the first operand) and the divisor (the second operand) of the modulo operator % are positive, the result is simply the remainder of the division operation. Here’s an example:
-
Python
x = 10 y = 3 result = x % y print("The remainder of ", x, " divided by ", y, " is ", result)
Output:
The remainder of 10 divided by 3 is 1
Explanation:
In this example, we are calculating 10 % 3. The result is 1, which is the remainder when 10 is divided by 3.
Example 2: Python Mod function with negative numbers
The modulo operator % in Python works differently with negative numbers compared to positive numbers. When the dividend (the first operand) is negative, the result of the modulo operation has the same sign as the divisor (the second operand). Here’s an example:
-
Python
x = -7 y = 3 result = x % y print("The remainder of ", x, " divided by ", y, " is ", result)
Output:
The remainder of -7 divided by 3 is 2
Explanation:
In this example, we are calculating -7 % 3. The result is 2, which is the same as the result of (-7) + 3 = -4. Note that the result is positive, even though the dividend is negative. This is because divisor 3 is positive.
Example 3: Python Mod function with floating-point numbers
In this example, we will use the mod function to calculate the remainder of a division operation between two floating-point numbers.
-
Python
x = 10.5 y = 3.2 result = x % y print("The remainder of ", x, " divided by ", y, " is ", result)
Output:
The remainder of 10.5 divided by 3.2 is 0.8999999999999995
Explanation:
In this example, we see that the mod function returns a floating-point value as the remainder.
Example 4: Python Mod Function using divmod()
The modulo operator % returns the remainder of a division operation between two numbers. We can use divmod() to implement the modulo operator as follows:
-
Python
def modulo_operator(dividend, divisor): quotient, remainder = divmod(dividend, divisor) return remainder print( modulo_operator(10, 3))
Output:
1
Explanation:
In this implementation, we first use divmod() to get the quotient and remainder of the division operation. Since we are interested in the remainder (i.e., the result of the modulo operation), we return the remainder value.
In this example, we are calculating 10 % 3, which is 1. The modulo_operator() function correctly returns 1.
Note: that the modulo_operator() function behaves the same way as the built-in % operator. However, using divmod() to implement the modulo operation may be useful in some situations where you also need to get the quotient of the division operation.
Example 5: Python Mod Function with fmod()
The modulo operator % works only for integers, but we can use the fmod() function from the math module to implement a modulo operator that works with floating-point numbers. Here’s an example implementation:
-
Python
import math def modulo_operator(dividend, divisor): return math.fmod(dividend, divisor) print(modulo_operator(5.5, 2.2))
Output:
1.1000000000000005
Explanation: In this implementation, we use the fmod() function from the math module to calculate the remainder of the division operation. The fmod() function returns the same result as the % operator, but it works with floating-point numbers.
In this example, we are calculating 5.5 % 2.2, which is 1.1. The modulo_operator() function returns 1.1000000000000005, which is the exact result of the calculation.
Note: that the fmod() function may have different behavior than the % operator for very large or very small numbers due to the limitations of floating-point arithmetic. Also, fmod() raises a ValueError if the second argument (divisor) is zero.
Example 6: Exception in Python Mod Function
In Python, the modulus operator % can raise a ZeroDivisionError exception if the divisor (the second operand) is zero. Here’s an example:
-
Python
x = 10 y = 0 result = x % y print("The remainder of ", x, " divided by ", y, " is ", result)
Output:
Traceback (most recent call last):
File "", line 5, in
ZeroDivisionError: integer division or modulo by zero
Explanation:
In this example, we are trying to calculate 10 % 0, which is not a valid operation because we cannot divide by zero. Python raises a ZeroDivisionError exception to indicate the error.
To handle this exception, we can use a try-except block like this:
-
Python
a = 10 b = 0 try: result = a % b except ZeroDivisionError: print("Error: division by zero")
Output:
Error: division by zero
Explanation:
In this example, we are trying to calculate the modulus operation of dividend % divisor. If divisor is zero, a ZeroDivisionError exception is raised, and we print an error message.
Note: If you are implementing a modulo operator using divmod() or math.fmod(), you may also need to handle a ZeroDivisionError exception when the divisor is zero.
Conclusion
In this article, we discussed the Python mod function and its usage to calculate the remainder of a division operation. We saw that the mod function works with positive, negative, and floating-point numbers, and returns the remainder as a single value. We have also learned about the divmod() and fmod(). The mod function is a useful tool in programming and can be used in various applications, such as calculating the modulo of a number, checking if a number is odd or even, and so on.
Frequently Asked Questions (FAQs)
Ques 1. What is the modulo function in Python?
Ans. The modulo function in Python is the % operator, which returns the remainder of a division operation.
Ques 2. What is the difference between the modulo operator and the floor division operator in Python?
Ans. The modulo operator % returns the remainder of a division operation, while the floor division operator // returns the quotient rounded down to the nearest integer.
Ques 3. How does the modulo operator work with negative numbers in Python?
Ans. When the dividend of the modulo operation is negative, the result has the same sign as the divisor. For example, -7 % 3 is 2, and 7 % -3 is -2.
Ques 4. What happens if the divisor of the modulo operation is zero in Python?
Ans. If the divisor is zero, Python raises a ZeroDivisionError exception.
Ques 5. Can I use the modulo operator with floating-point numbers in Python?
Ans. Yes, you can use the math.fmod() function to calculate the remainder of a division operation with floating-point numbers.
Ques 6. How can I handle exceptions when using the modulo operator in Python?
Ans. You can use a try-except block to handle exceptions, such as ZeroDivisionError when the divisor is zero.
Ques 7. What is the modulo operator used for in programming?
Ans. The modulo operator is often used in programming for tasks such as finding the remainder of a division operation, calculating the position of an element in a circular array and determining whether a number is even or odd.
When we see a ‘%’ the first thing that comes to our mind is the “percent” but in computer language, it means modulo operation(%) which returns the remainder of dividing the left-hand operand by right-hand operand or in layman’s terms it finds the remainder or signed remainder after the division of one number by another.
Given two positive numbers, a and n, a modulo n (a % n, abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
The Python Modulo Operator
Basically, the Python modulo operation is used to get the remainder of a division. The modulo operator(%) is considered an arithmetic operation, along with +, –, /, *, **, //. In most languages, both operands of this modulo operator have to be an integer. But Python Modulo is versatile in this case. The operands can be either integers or floats.
Syntax:
a % b
Here, a is divided by b, and the remainder of that division is returned.
Example 1:
Modulo Operator With integer.
Python3
a
=
13
b
=
5
c
=
a
%
b
print
(a,
"mod"
, b,
"="
,
c, sep
=
" "
)
Example 2:
Modulo Operator With float with a negative number.
Python3
d
=
15.0
e
=
-
7.0
f
=
d
%
e
print
(d,
"mod"
, e,
"="
,
f, sep
=
" "
)
Output:
13 mod 5 = 3 15.0 mod -7.0 = -6.0
Example 3:
Suppose, we want to calculate the remainder of every number from 1 to n when divided by a fixed number k.
Python3
def
findRemainder(n, k):
for
i
in
range
(
1
, n
+
1
):
rem
=
i
%
k
print
(i,
"mod"
, k,
"="
,
rem, sep
=
" "
)
if
__name__
=
=
"__main__"
:
n
=
5
k
=
3
findRemainder(n, k)
Output:
1 mod 3 = 1 2 mod 3 = 2 3 mod 3 = 0 4 mod 3 = 1 5 mod 3 = 2
ZeroDivisionError in Python
The only Exception you get with the Python modulo operation is ZeroDivisionError. This happens if the divider operand of the modulo operator becomes zero. That means the right operand can’t be zero. Let’s see the following code to know about this python exception.
Python3
a
=
14
b
=
0
try
:
print
(a,
'mod'
, b,
'='
,
a
%
b, sep
=
" "
)
except
ZeroDivisionError as err:
print
(
'Cannot divide by zero!'
+
'Change the value of the right operand.'
)
Output:
Cannot divide by zero! Change the value of the right operand.
Last Updated :
11 Apr, 2023
Like Article
Save Article
Как и в других языках программирования, оператор модуля Python выполняет ту же работу по нахождению модуля заданного числа. Оператор представляет собой математический символ, используемый для выполнения различных операций, таких как(+, -, * /) сложение, вычитание, умножение и деление над заданными двумя числами, чтобы вернуть результат в виде целого числа, а также числа с плавающей запятой.
Оператор указывает компилятору выполнить определенные действия на основе переданного символа оператора для данного числа.
Оператор модуля
Оператор модуля Python – это встроенный оператор, который возвращает оставшиеся числа путем деления первого числа на второе. Он также известен как Python modulo. В Python символ модуля представлен в виде символа процента(%). И называется он оператором остатка.
Ниже приведен синтаксис для получения остатка путем деления первого числа на второе.
Rem = X % Y
Здесь X и Y – два целых числа, а модуль(%) используется между ними, чтобы получить остаток, где первое число(X) делится на второе число(Y).
Например, у нас есть два числа, 24 и 5. И мы можем получить остаток, используя модуль или оператор по модулю между числами 24% 5. Здесь 24 делится на 5, что возвращает 4 в качестве остатка и 4 в качестве частного. Когда первое число полностью делится на другое число, не оставляя остатка, результатом будет 0.
Получение остатка двух целых чисел с помощью цикла while
Давайте напишем программу для получения остатка от двух чисел, используя цикл while и оператор модуля(%) в Python.
Get_rem.py
while True: # if the while condition is true if block is executed a = input('Do you want to continue or not(Y / N)? ') if a.upper() != 'Y': # If the user pass 'Y', the following statement is executed. break a = int(input(' First number is: ')) # first number b = int(input(' Second number is: ')) # second number print(a, ' % ', b, ' = ', a % b) # perform a % b print(b, ' % ', a, ' = ', b % a) # perform b % a
Выход:
Do you want to continue or not(Y / N)? Y First number is: 37 Second number is: 5 37 % 5 = 2 5 % 37 = 5 Do you want to continue or not(Y / N)? Y First number is: 37 Second number is: 5 24 % 5 = 4 5 % 24 = 5 Do you want to continue or not(Y / N)? Y First number is: 37 Second number is: 5 28 % 5 = 3 5 % 28 = 5
Остаток двух чисел с плавающей запятой
Напишем программу, чтобы найти остаток от двух целых чисел, используя оператор модуля в Python.
Mod.py
x = float(input('First number: ')) y = float(input(' Second number: ')) res = x % y # store the remainder in res variable print("Modulus of two float number is: ", x, "%", y, " = ", res, sep = " ")
Выход:
First number: 40.5 Second number: 20.5 Modulus of two float number is: 40.5 % 20.5 = 20.0
Отрицательного числа
Давайте напишем программу, чтобы получить остаток от двух отрицательных чисел, используя цикл while и оператор модуля(%) в Python.
Mod.py
while True: x = input(' Do you want to continue(Y / N)? ') if x.upper() != 'Y': break # input two integer number and store it into x and y x = int(input(' First number: ')) y = int(input(' Second number: ')) print("Modulus of negative number is: ", x, "%", y, " = ", x % y, sep = " ") print("Modulus of negative number is: ", y, "%", x, " = ", y % x, sep = " ")
Выход:
First number: -10 Second number: 3 Modulus of negative number is: -10 % 3 = 2 Modulus of negative number is: 3 % -10 = -7 Do you want to continue(Y / N)? N
Нахождение остатка двух чисел с помощью функции fmod()
Рассмотрим программу, как получить остаток от двух чисел с плавающей запятой, используя функцию fmod() в Python.
Fmod.py
import math # import math package to use fmod() function. res = math.fmod(25.5, 5.5) # pass the parameters print("Modulus using fmod() is:", res) ft = math.fmod(75.5, 15.5) print(" Modulus using fmod() is:", ft) # take two integer from the user x = int( input( "First number is")) y = int(input("Second number is ")) out = math.fmod(x, y) # pass the parameters print("Modulus of two numbers using fmod() function is", x, " % ", y, " = ", out)
Выход:
Modulus using fmod() is: 3.5 Modulus using fmod() is: 13.5 First number is 24 Second number is 5 Modulus of two numbers using fmod() function is 24 % 5 = 4.0
n чисел с помощью функции
Давайте напишем программу на Python, чтобы найти модуль n чисел с помощью функции и цикла for.
getRemainder.py
def getRemainder(n, k): for i in range(1, n + 1): # Store remainder in the rem variable when i is divided by k number rem = i % k print(i, " % ", k, " = ", rem, sep = " ") # use _name_ driver code if __name__ == "__main__": # define the first number for displaying the number up to desired number. n = int(input("Define a number till that you want to display the remainder ")) k = int( input(" Enter the second number ")) # define the divisor # call the define function getRemainder(n, k)
Выход:
Define a number till that you want to display the remainder 7 Enter the second number 5 1 % 5 = 1 2 % 5 = 2 3 % 5 = 3 4 % 5 = 4 5 % 5 = 0 6 % 5 = 1 7 % 5 = 2
Заданного массива с помощью функции mod()
Напишем программу для демонстрации функции mod() в Python.
Mod_fun.py
import numpy as np # import numpy package x = np.array([40, -25, 28, 35]) # define first array y = np.array([20, 4, 6, 8]) # define second array # call mod() function and pass x and y as the parameter print("The modulus of the given array is ", np.mod(x, y))
Выход:
The modulus of the given array is [0 3 4 3]
Как мы видим в приведенной выше программе, переменные x и y содержат массивы. После этого мы используем функцию mod() для передачи x и y в качестве параметра массива, который делит первый массив(x) на второй массив(y), а затем возвращает остаток чисел.
Нахождение модуля двух чисел, используя numpy
Давайте рассмотрим программу для импорта пакета numpy из библиотеки Python, а затем воспользуемся функцией остатка для получения модуля в Python.
Num.py
import numpy as np # import numpy package as np # declaration of the variables with their values num = 38 num2 = 8 res = np.remainder(num, num2) # use np.remainder() function print( "Modulus is", num, " % ", num2, " = ", res) # display modulus num % num2
Выход:
Modulus is 38 % 8 = 6
В Python, когда число делится на ноль, возникает исключение, которое называется ZeroDivisionError. Другими словами, он возвращает исключение, когда число делится на делитель, равный нулю. Следовательно, если мы хотим удалить исключение из оператора модуля Python, делитель не должен быть равен нулю.
Напишем программу для демонстрации оператора Python Exception in Modulus.
Except.py
x = int(input(' The first number is: ')) y = int(input(' The second number is: ')) # display the exception handling try: # define the try print(x, ' % ', y, ' = ', x % y) except ZeroDivisionError as err: # define the exception print('Cannot divide a number by zero! ' + 'So, change the value of the right operand.' )
Выход:
The first number is: 24 The second number is: 0 Cannot divide a number by zero! So, change the value of the right operand.
Как видно из приведенного выше результата, он отображает: «Невозможно разделить число на ноль! Поэтому измените значение правого операнда». Следовательно, мы можем сказать, что когда мы делим первое число на ноль, оно возвращает исключение.
Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.
Статья содержит описание основных операторов языка python, таких как остаток от деления python, логические, побитовые операторы и т.д. Приведены примеры использования операторов и пояснены некоторые тонкости их использования.
Содержание
- Введение в операторы Python
- Арифметические операторы Python
- Сложение
- Вычитание
- Умножение
- Деление
- Возведение в степень
- Деление без остатка
- Деление по модулю (остаток от деления)
- Операторы сравнения
- Оператор «меньше»
- Оператор «больше»
- Оператор «меньше или равно»
- Оператор «больше или равно»
- Оператор «равно»
- Оператор «не равно»
- Операторы присваивания
- Простое присваивание
- Сложение и присваивание
- Вычитание и присваивание
- Деление и присваивание
- Умножение и присваивание
- Деление по модулю и присваивание
- Возведение в степень и присваивание
- Деление с остатком и присваивание
- Логические операторы python
- И (and)
- Или (or)
- Не (not)
- Операторы принадлежности (членства)
- В (in)
- Нет в (not in)
- Операторы тождественности
- Это (is)
- Это не (is not)
- Битовые операторы python
- Бинарное «и»
- Бинарное «или»
- Бинарное «или нет»
- Инвертирующий оператор
- Бинарный сдвиг влево
- Бинарный сдвиг вправо
Введение в операторы Python
В языке программирования python, как и во всех остальных, есть различные операторы. Большинство из них выглядят стандартно и привычно: арифметические операции везде обозначаются одинаково, а, например, для остатка от деления в python зарезервирован знак %. Но рассмотрим же подробнее все стандартные и наиболее часто используемые операторы языка python.
Операторы языка Питон подразделяются на 7 видов:
- Знаки арифметических операций
- Сравнительные
- Присваивающие
- Логические
- Операторы принадлежности (или членства, или вложенности)
- Тождественные
- Битовые (или бинарные)
Арифметические операторы Python
Данные операторы выполняют операции сложения, умножения, вычитания, деления, вычисления остатка от деления и возведения в степень над числами. Сложение и умножение также работает и для строк.
Рассмотрим примеры работы различных операторов (в качестве среды разработки в примерах используется Visual Studio 2019). Синтаксис python позволяет сразу же вычислять результат операции без присвоения его какой-либо переменной; это свойство будет использовано в некоторых примерах. Также не нужно производить import каких-либо библиотек: все основные команды python являются стандартными и зарезервированными.
Сложение
Складываем один и два:
Вычитание
Вычитаем из четырёх два:
Умножение
Умножаем десять на пять:
print(10 * 5)
# Вывод:
50
Деление
Делим двадцать четыре на шесть:
print(24 / 6)
# Вывод:
4.0
Примечание. Результат деления в Python 3 и выше всегда приводится к типу float (число с плавающей запятой), который требует большее количество памяти, чем, например, целочисленный тип int, в связи с чем деление (и другие операции) в питон работает медленнее, чем в более низкоуровневых языках.
Возведение в степень
Возводим семь во вторую степень (или в квадрат):
print(7 ** 2)
# Вывод:
49
Деление без остатка
Ищем целую часть от деления семи на два:
Примечание. Python отличается от других языков тем, что в нём результат целочисленного деления может быть как целым числом, так и числом с плавающей запятой. Например, если поделить число типа int на число типа float, то результатом будет число типа float:
print(70 // 2.0)
# Вывод:
35.0
Одно из чисел вещественное в этом — в этом и состоит загвоздка. В таком случае ответ обязан быть вещественным числом.
Деление по модулю (остаток от деления)
Ищем остаток от деления семи на два:
Операторы сравнения
Эти операторы сравнивают 2 значения (строковые или числовые). Любой из операторов данного типа возвращает булевое значение — True или False.
Оператор «меньше»
print(13 < 15)
# Вывод:
True
13 меньше, чем 15 — это верно.
print(13 < 12)
# Вывод:
False
13 меньше, чем 12 — это не верно.
Оператор «больше»
print(13 > 13)
# Вывод:
False
13 меньше, чем 13 — это не верно.
print(13 > 10)
# Вывод:
True
13 меньше, чем 10 — это верно.
Оператор «меньше или равно»
print(13 <= 17)
# Вывод:
True
13 меньше или равно 17 — это верно.
print(13 <= 1)
# Вывод:
False
13 меньше или равно 1 — это не верно.
Оператор «больше или равно»
print(13 >= 13)
# Вывод:
True
13 большее или равно 13 — это верно.
print(13 >= 17)
# Вывод:
False
13 большее или равно 17 — это не верно.
Оператор «равно»
print(13 == 13)
# Вывод:
True
13 равно 13 — это верно.
print(13 == 14)
# Вывод:
False
13 равно 14 — это не верно.
Оператор «не равно»
print(13 != 13)
# Вывод:
False
13 не равно 13 — это не верно.
print(13 != 14)
# Вывод:
True
13 не равно 14 — это верно.
Операторы присваивания
Эти операторы присваивают значение правого операнда левому. Только один-единственный оператор просто присваивает значение — это знак «=» (равно). Все остальные предварительно выполняют какое-либо арифметическое действие между двумя операндами, и получившийся результат записывается в левый операнд.
Простое присваивание
Присвоим переменным значения, с которыми будут работать другие операторы дальше:
a = 100
b = 25
print(a, b)
# Вывод:
100 25
Сложение и присваивание
Значение переменной b складывается со значением переменной a, после чего результат записывается в a:
a += b
print(a)
# Вывод:
125
Вычитание и присваивание
Значение переменной b вычитается из значения переменной a, после чего результат записывается в a:
a -= b
print(a)
# Вывод:
75
Деление и присваивание
Значение переменной a делится на значение переменной b, после чего результат записывается в a:
a /= b
print(a)
# Вывод:
4.0
Умножение и присваивание
Значение переменной a умножается на значение переменной b, после чего результат записывается в a:
a *= b
print(a)
# Вывод:
2500
Деление по модулю и присваивание
Значение переменной a делится на значение переменной b, после чего остаток от деления записывается в a:
a %= b
print(a)
# Вывод:
0
a = 68
b = 23
a %= b
print(a)
# Вывод:
22
Возведение в степень и присваивание
Значение переменной a возводится в степень, равную значению переменной b, после чего результат записывается в a:
a **= b
print(a)
# Вывод:
100000000000000000000000000000000000000000000000000
Деление с остатком и присваивание
Значение переменной a делится на значение переменной b, после чего целая часть результата деления записывается в a:
a //= b
print(a)
# Вывод:
4
a = 68
b = 23
a //= b
print(a)
# Вывод:
2
Логические операторы python
Логических операторов в python, как и в математической логике, всего 3 — «и», «или», «не», в Python это их английские аналоги — and, or, not. Результат выполнения этих операций соответствует таблице истинности.
И (and)
a = (1 + 3 == 4) and (2 * 2 == 6)
print(a)
# Вывод:
False
Результатом этой операции оказалось False, так как для оператора and необходимо, чтобы оба операнда были равны True. Тогда и только тогда вернётся True.
Или (or)
a = (1 + 3 == 4) or (2 * 2 == 6)
print(a)
# Вывод:
True
Результатом этой операции оказалось True, ведь для оператора «or» достаточно, чтобы лишь один из операндов был равен True.
Не (not)
a = (1 + 3 == 4) and not (2 * 2 == 6)
print(a)
# Вывод:
True
Так как наш «неверный» правый операнд в результате применения к нему операции not изменил своё значение на True, то верным стало и всё выражение целиком.
Операторы принадлежности (членства)
Эти операторы проверяют, существует ли заданное значение в известном списке, словаре, кортеже или строке. Можно сказать, что таковых в питон всего 2 — это in и его отрицание not in. Соответственно, in вернёт True в случае наличия элемента в последовательности, а not in, наоборот, вернёт False, если данный элемент есть в последовательности, и True, если его нет.
В (in)
a = "abc" in "abcdef"
print(a)
# Вывод:
True
Строка «abc» является подстрокой строки «abcdef», соответственно, являясь подпоследовательностью данной последовательности.
a = 10 in (1, 7, 13, 6)
print(a)
# Вывод:
False
Числа 10 нет в этом списке, потому мы и видим False.
Нет в (not in)
a = 10 not in (1, 7, 13, 6)
print(a)
# Вывод:
True
Элемента 10 нет в данном списке, поэтому операция вернёт True. А если он будет:
a = 10 not in (1, 7, 13, 6, 10)
print(a)
# Вывод:
False
В этом списке уже есть значение 10, поэтому оператор непринадлежности возвращает False.
a = "abc" not in "abcdef"
print(a)
# Вывод:
False
Операторы тождественности
Их, как и операторов принадлежности, всего два, и один из них является отрицанием другого. Оператор в python is сравнивает положение двух объектов в памяти и выясняет, один и тот же ли это объект, в случае успеха возвращая True. Оператор not is вернёт True, если проверка показала, что сравниваемые объекты являются разными (имеют разное расположение в памяти).
Это (is)
print("10" is '10')
# Вывод:
True
Разные кавычки не влияют на результат выполнения операции, так как это в любом случае строка, один и тот же объект. Но если сравнить строку и число, результат будет иным:
print(10 is '10')
# Вывод:
False
Это действительно разные объекты, находящиеся в разных местах памяти.
Это не (is not)
print(20 is not (20 + 1))
# Вывод:
True
Верно, ведь 20 не равно 21.
Битовые операторы python
Побитовые python операторы работают только с целыми числами, причём особым образом: значения операндов переводятся в двоичную систему, после чего операция выполняется последовательно для каждого бита. После окончания операции значение переводится обратно в десятичную систему и может быть возвращено в качестве результата операции.
Всего в питон 6 побитовых операторов:
- & — бинарное «и»
- | — бинарное «или»
- ^ — бинарное «или нет» (исключающее ИЛИ, или XOR)
- ~ — инвертирующий оператор (отрицание, для него требуется только один операнд)
- << — бинарный сдвиг влево
- >> — бинарный сдвиг вправо
Бинарное «и»
Бинарное «или»
Бинарное «или нет»
Инвертирующий оператор
Бинарный сдвиг влево
Бинарный сдвиг вправо
In mathematics, the modulo gives you the remainder of the division. In Python, you can calculate the modulo using the percentage operator %.
For example:
>>> 10 % 4 2
You can interpret this answer as to how many slices of pizza are left over when 10 slices are shared with four eaters. The answer is 10 % 4, which is 2.
In Python, the modulo has many practical use cases. The most common use cases include checking if a number is odd/even, or checking if a number is a prime number.
In this guide, you will learn everything you need about modulo and its usage in Python.
Modulo in Mathematics
In mathematics, modulo is used to describe the remainder in the division between two numbers. The modulo is commonly denoted with the mod.
a mod b
Where:
- a is the dividend.
- b is the divisor.
The result of the modulo operation is the remainder in the division between the dividend and the divisor.
For example:
7 mod 3 = 1
To see why this is the case, think about sharing 7 apples with 3 persons:
You can divide 6 apples for 3 persons evenly such that each person has 2 apples. But one apple will be left over. This one leftover is the remainder in the division that you can compute using modulo.
Another great example of modular arithmetic is a 12-hour clock. When you count the time with a 12-hour clock, you count up to 12, but then you go back to 0.
For example, to know the time on a 12-hour clock say 11 hours after 7:00, you cannot add 11 to 7:00, because that would give 18. This is not possible on a 12-hour clock. Instead, you need to add the 11 hours to 7:00 until you reach 12. Then the 6 leftover hours are added to the new round to make it to 6:00.
This is exactly what the modulo does.
So a shorter way to determine the number of hours on a 12-hour clock is by taking modulo 12 from the number of (total) hours.
For example, 18:00 can be converted to a 12-hour clock by:
18 mod 12 = 6
This implies that in a 12-hour clock 18:00 and 6:00 are the same thing. A more mathematical way to express this equivalence would be:
18 ≡ 6 (mod 12)
This reads as “18 and 6 are congruent to modulo 12”. The interpretation is that 12-modulo-wise, numbers 18 and 6 are equal because of the same remainder in the division when divided by 12.
Generally, in modular arithmetic, you can express these modular relationships by:
a ≡ b (mod n)
Which means “a and b are congruent to modulo n”.
Ok, this is enough for the maths part. Now that you understand how the modulo works in mathematics, let’s switch back to Python mode.
In Python, there is a dedicated modulo operator, the percentage operator %.
To calculate the modulo between two numbers, add the % operator in-between the two numbers:
a % b
In Python, you can calculate the modulos of numeric types int and float. Also, you can calculate the modulo of negative numbers.
Modulo with Integers in Python
The most common use case for calculating modulos is calculating it for integers.
Given two positive integers, the modulo operation in Python returns the remainder in the division.
Here are some examples:
>>> 4 % 3 1 >>> 10 % 7 3 >>> 78 % 14 8 >>> 1000 % 10 0
Meanwhile, the result of the modulo can be 0, you cannot take a modulo with 0. Similar to when you divide by 0, you will get a ZeroDivisionError when taking the modulo of 0.
For example:
>>> 5 % 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
Cool, now you know how to use modulo on positive integers in Python.
Next, let’s take a look at taking modulo between two negative integers.
Modulo of a Negative Numbers
Calculating modulos of negative numbers is possible in Python.
But here is where it gets interesting. Different programming languages calculate negative modulos a bit differently. This is because it is unclear whether the result should have the sign of the dividend or the divisor.
For example, in JavaScript, the result of modulo takes the sign of the dividend (the value on the left):
console.log(7 % -4) // 3
Whereas in Python, the result has the sign of the divisor (the value on the right):
>>> 7 % -4 -1
But why are the results not the same?
This boils down to how the modulo is calculated in these languages. As it turns out, the modulo is calculated differently in JavaScript as opposed to Python:
javascript: r = a - (b * trunc(a / b)) python: r = a - (b * floor(a / b))
In both of these equations:
- r is the remainder of division.
- a is the dividend.
- b is the divisor.
The difference is between these two lines in the last term. In JavaScript, the last term is trunc(a / b). In Python, it is floor(a / b).
- trunc(a / b) means a truncated division. This rounds a negative number toward 0.
- floor(a / b) means floor division. This rounds a negative number away from 0.
However, with positive numbers, the floor() and trunc() work the same way. They both round down to the nearest integer value (that is, toward 0).
This is what causes the differences in the results between calculating modules of negative numbers in JavaScript and Python.
To support the understanding, let’s calculate 7 % -4 step-by-step using the modulo equation in both of these languages.
In JavaScript:
r = a - (b * trunc(a / b)) a = 7 b = -4 r = 7 - (-4 * trunc(7 / -4)) = 7 - (-4 * trunc(-1.75)) = 7 - (-4 * -1) = 7 - 4 = 3
In Python:
r = a - (b * floor(a / b)) a = 7 b = -4 r = 7 - (-4 * floor(7 / -4)) = 7 - (-4 * floor(-1.75)) = 7 - (-4 * -2) = 7 - 8 = -1
Now you know why and how the JavaScript version gives you 3 whereas the Python version gives you -1.
Modulo with Floats
Similar to performing a modulo between two integers, you can calculate the modulo between two floats. This also results in the remainder in the division, just like you would expect.
Here are some examples:
>>> 10.5 % 4.5 1.5 >>> 10 % 1.5 1.0 >>> 12.5 % 3.5 2.0 >>> 10.0 % 3.0 1.0
However, when calculating modulos with floats, according to the docs, use math.fmod() function instead.
For example:
>>> import math >>> math.fmod(10.5, 4.5) 1.5 >>> math.fmod(10, 1.5) 1.0 >>> math.fmod(12.5, 3.5) 2.0 >>> math.fmod(10.0, 3.0) 1.0
Similar to other arithmetic operations in Python, you may encounter floating-point accuracy issues with modulos.
For example:
>>> math.fmod(10.0, 3.1) 0.6999999999999997 >>> 10.0 % 3.1 0.6999999999999997
Modulo and the divmod() Function
In Python, there is a built-in function divmod(). It takes two parameters, the dividend, and the divisor. It returns a tuple that contains two values:
- The result of a floor division.
- The remainder in the division, that is, the modulo.
Example. Given 7 apples and 3 workers, how many apples does each worker get and how many apples will be left over?
To answer this question, you can directly use the divmod() function. It returns both the number of fairly shared items and the number of leftovers:
>>> divmod(7, 3) (2, 1)
Here:
- Result 2 is obtained by calculating 7 // 3 (floor division).
- Result 1 is obtained by calculating 7 % 3 (modulo).
So far you have seen built-in mechanisms to calculate modulos with integers, floats, and negative values in Python. Next, let’s take a look at the order in which the modulos are calculated when forming chains of modulos.
Operator Precedence – Chains of Modulos in Python
In Python, the modulo operator % has the same precedence level as multiplication (*), division (/), and floor division (//).
This means that if you multiply, and then take a modulo, the multiplication is performed first, and then the modulo operation, and vice versa.
But if you add two numbers and then take a modulo, the modulo will precede.
Let’s see an example:
>>> 3 * 4 % 5 - 6 -4
To understand how this is obtained, put parenthesis around the terms in the correct precedence order:
>>> ((3 * 4) % 5) - 6 -4
Here is the step-by-step calculation of the above:
- 3 * 4 % 5 – 6
- ((3 * 4) % 5) – 6
- (12 % 5) – 6
- 2 – 6
- -4
Now you should have a pretty good idea about the modulo in general, and how to calculate modulos in Python. Next, let’s jump into the actual use cases of calculating modulo in Python.
Common Use Cases of Modulo in Python
There is a big number of use cases for modulo in Python. A common example is to check whether a number is odd or even. Another popular task is to check if a number is a prime number. Let’s see these and many other useful applications of modulo in Python.
Periodicity in Code
Using modulo is useful when there is periodicity in your code.
Think about a game character that runs out of the screen on the right side and pops back in on the left side. The code that makes this possible defines the player’s x-position as arithmetic modulo screen width.
In other words, when the player’s x position exceeds the width of the screen, the modulo operation resets it back to 0.
x_pos = x_pos % screen_width
Let’s see a more concrete example of this cyclic behavior in Python code by going back to the 12-hour clock.
A 12-hour clock wraps around itself 12 hours before the day is over. But it is still a perfectly valid way to track time. This is possible because 15:00 on a 24-hour clock is displayed as 3:00 on a 12-hour clock. So for each hour in the day, there is a corresponding time in the 12-hour clock.
To write a Python program that displays the hours of the day in a 12-hour clock, you need to take a modulo 12 of the hour. This means 12 becomes 0, 13 becomes 1, 14 becomes 2, and so on.
Here is how it looks in the code:
def wallclock(hour): result = hour % 12 print(f"{hour}:00 is {result}:00 on a 12-hour clock ") # Let's print each hour in a day: for hour in range(25): wallclock(hour)
Output:
0:00 is 0:00 on a 12-hour clock 1:00 is 1:00 on a 12-hour clock 2:00 is 2:00 on a 12-hour clock 3:00 is 3:00 on a 12-hour clock 4:00 is 4:00 on a 12-hour clock 5:00 is 5:00 on a 12-hour clock 6:00 is 6:00 on a 12-hour clock 7:00 is 7:00 on a 12-hour clock 8:00 is 8:00 on a 12-hour clock 9:00 is 9:00 on a 12-hour clock 10:00 is 10:00 on a 12-hour clock 11:00 is 11:00 on a 12-hour clock 12:00 is 0:00 on a 12-hour clock 13:00 is 1:00 on a 12-hour clock 14:00 is 2:00 on a 12-hour clock 15:00 is 3:00 on a 12-hour clock 16:00 is 4:00 on a 12-hour clock 17:00 is 5:00 on a 12-hour clock 18:00 is 6:00 on a 12-hour clock 19:00 is 7:00 on a 12-hour clock 20:00 is 8:00 on a 12-hour clock 21:00 is 9:00 on a 12-hour clock 22:00 is 10:00 on a 12-hour clock 23:00 is 11:00 on a 12-hour clock 24:00 is 0:00 on a 12-hour clock
Odd or Even?
To check if a number is odd or even, use the modulo. This is because if the number is even, it is evenly divisible by 2. In other words, number mod 2
yields 0.
For example, here is a function that checks if a number is even:
def is_even(number): return number % 2 == 0
Now you can use this function on any number:
print(is_even(10)) print(is_even(7))
Output:
True False
And to check if a number is odd, you can either use the is_even() function with negation:
def is_odd(number): return not is_even(number)
Or you can use the fact that any odd number modulo 2 gives a remainder of division of 1:
def is_odd(number): return number % 2 == 1
Now you can use this function to check if number inputs are odd:
print(is_odd(10)) print(is_odd(7))
Output:
False True
Prime Number
A prime number is any number greater than 1, that can only be divided by 1 and by itself.
To check if a number is a prime number, you need to check if any number less than the target divides it evenly. If the division leaves no remainder, the number is a prime number because it is evenly divisible. As you learned already, to check if a division leaves a remainder, use modulo.
Here is a Python program that checks if a given number is a prime number:
def is_prime(num): if num > 1: # Check if any number less than 'num' divides it evenly for i in range(2, num): if num % i == 0: print(f"{num} is not a prime number") break else: print(f"{num} is a prime number") else: print(f"{num} is not a prime number")
Example calls:
is_prime(10) is_prime(7)
Output:
10 is not a prime number 7 is a prime number
Grouping Items
Let’s group a list of items into a list of n chunks.
If the size of the list is evenly divisible by the number of chunks (such as 9 items to 3 chunks), the task is trivial.
def chunk_naive(items, n_groups): groups = [] for i in range(0, len(items), n_groups): groups.append(items[i: i + n_groups]) return groups
Example run:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] grouped = chunk_naive(numbers, 5) print(grouped)
Output:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
But the problems arise when you try to naively group a list into an indivisible number of chunks:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] grouped = chunk_naive(numbers, 4) print(grouped)
This should result in four chunks, but instead, it only gives you three:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
To overcome this issue, use modular arithmetic to determine the number of items to add to each chunk.
To keep it short, I’ve added comments to the code that make the process easy to follow. Also, beneath this, there is a more elegant implementation of the very same algorithm.
def chunk(items, n_groups): # The starting index of a group i = 0 # The nuber of ungrouped items count = len(items) # The grouped items result groups = [] # Loop through the chunk numbers in reversed order # For example, with 3 chunks the chunks are # 3, 2, 1 in the reversed looping order. for group in reversed(range(1, n_groups + 1)): # Count the number of elements in this group by # dividing the number of ungrouped items by the group number result = count // group # Count the leftover items from this group remainder = count % group # Determine the index for the last item in this chunk. # If the remainder is 0, it is the number of elements in this group # If the remainder is non-zero, add one to the index. last = result + int(bool(remainder)) # Create + add a group from start i to the last index in this chunk groups.append(items[i:i + last]) # advance the start of the next chunk to the last point of this group i += last # reduce the number of ungrouped items. count -= last # Return the grouped elements. return groups
Example call:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] grouped = chunk(numbers, 3) print(grouped)
Now the number of chunks is right no matter what.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
By the way, the chunk() function can be made a bit cleaner by:
- Removing the comments.
- Replacing the floor division and modulo with the divmod() function.
- Replacing return with yield, that is, turning the function into a generator.
Here is how the improved version looks:
def chunk(items, n_groups): i = 0 count = len(items) for group in reversed(range(1, n_groups + 1)): result, remainder = divmod(count, group) last = result + int(bool(remainder)) yield items[i:i + last] i += last count -= last
Now because you use a generator, you need to convert the iterator object returned by the generator into a list to see the result easily. Other than that, you can run the same code as in the previous example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] grouped = list(chunk(numbers, 3)) print(grouped)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Repeat the Code in Intervals
Sometimes, when looping, you may not want to run code at each iteration. Instead, you may want to specify an interval on how often a code should be run.
To run code in intervals in a loop, check if the current iteration index is evenly divisible by the interval. In other words, perform a modulo with the current iteration index and the interval.
For instance, let’s print every third number in a range of numbers:
numbers = list(range(21)) i = 0 interval = 3 while i < len(numbers): if i % interval == 0: print(i) i += 1
Output:
0 3 6 9 12 15 18
Advanced Use of Modulo in Python
Before wrapping up, I’d like to show you the advanced use of the modulo in Python. More specifically, you are going to learn how to perform modulo operation between two instances of a custom class.
The __mod__ method in Python
The __mod__() method is a special method in Python. It allows you to define what happens when you call modulo on two custom objects. This method is implemented into your custom class.
Let’s jump right into an example. In this example, you have a NumStr class, that represents numbers as strings:
class NumStr: def __init__(self, value): self.value = value
Let’s create two NumStr objects:
n1 = NumStr("10") n2 = NumStr("3")
Now, let’s apply the modulo operator between the two:
rem = n1 % n2
But this causes an error. A no-brainer.
Traceback (most recent call last): File "<string>", line 8, in <module> TypeError: unsupported operand type(s) for %: 'NumStr' and 'NumStr'
The error message is clear. It is not possible to take modulos between two NumStr objects. What may be surprising is that it is indeed possible to make this work.
Before showing you how to support modulo in custom objects, let’s dig into some details about calling operators on Python objects in the first place.
Whenever you call % between two integers, you are invoking a method called __mod__() under the hood. This is a type-specific method that specifies what happens when you call % on two objects.
In other words, this:
10 % 3
Is equivalent to this:
(10).__mod__(3)
The __mod__() method is implemented into the int type in Python. This means that in the int class, there is a method called __mod__() that implements the behavior of the modulo operation.
What is sometimes useful is that Python allows you to override this __mod__() method in your class. This means you get to decide what happens when the % operator is called on your custom objects.
Now, let’s go back to the NumStr class you implemented a while ago. The goal was to compute the modulo between two NumStr objects, right? To do this, you can override the __mod__() method in your NumStr class.
Here is an example of how to do it:
class NumStr: def __init__(self, value): self.value = value def __mod__(self, other): n1 = int(self.value) n2 = int(other.value) rem = n1 % n2 return NumStr(str(rem))
Here, the __mod__() method:
- Takes itself and another NumStr object as its arguments.
- Grabs the numeric string values and converts them to integers.
- Performs the modulo between the integers to get the remainder in the division.
- Returns a new NumStr object that represents the remainder in the division as a string.
Now you can apply the modulo operation on your NumStr objects:
n1 = NumStr("10") n2 = NumStr("3") rem = n1 % n2 print(rem.value)
Output:
1
As you can see, this produces the correct result.
Conclusion
Today you learned how to calculate and work with modulo in Python.
To recap, a modulo b in mathematics calculates the remainder in the division between a and b.
For example, 7 mod 3
represents sharing 7 apples with 3 workers evenly. The result of 7 mod 3
is 1, that is, one apple is going to be leftover.
- In Python, a common way to calculate modulo is using the dedicated modulo operator %.
- Alternatively, if you want to know both the result of the division and the remainder, you can use the built-in divmod() function.
- When doing modular arithmetic with floats, use the math module’s fmod() function.
Modulos also work for negative numbers in Python. However, the way negative modulos are calculated can differ from language to language.
There are many use cases for modulo in Python. For example, to figure out if a number is odd or even, you need to use modulo. Another common use case for modulo is to check if a number is a prime number.
Thanks for reading.
Happy coding!
Further Reading
- 50 Python Interview Questions
- Python Program to Check If a Number Is Odd or Even
About the Author
-
I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts