Using the Python Modulo % Operator

preview_player
Показать описание
Python supports a wide range of arithmetic operators that you can use when working with numbers in your code. One of these operators is the modulo operator (%), which returns the remainder of dividing two numbers. Modular operations are useful to check if a number is even or odd, simplifying cycling through data, and doing non-decimal based units conversion.

Python’s % operator’s been around for a long time. The code shown you has all been tested using Python 3.9, but you should be able to use it in pretty much any version of Python.

Рекомендации по теме
Комментарии
Автор

That is a brief explanation, no one has ever taught me about the modular arithmetic like this. Thanks for your effort really great and helpful videos. Please provide us a playlist for learning python from the scratch.

sourabhch
Автор

Thanks so much. After following the explanation, I think a % b = a - b * (a // b) which yields a remainder, congruent is the same remainder.

Congruence:
12.5% -5.5 = -4.0
-15 % -11 = -4

12.5 - (-5.5) * (12.5 // -5.5) == -15 - (-11) * (-15 // -11) -> True

pujipangesty
Автор

Thank you! You are a true human being for helping other humans! You shall be rewarded.

Zoheb
Автор

Note that Python’s modulo operator is defined in a sensible way. That means the result has the same sign as the divisor:

>>> (-5) % 3
1
>>> (-4) % 3
2

In some other languages, you would get the answers -2 and -1 instead.

Trivia question: if your language’s modulo operator is broken, how would you wrap it in a simple expression to get the Python-style answer?

lawrencedoliveiro
Автор

Thank you for putting this tutorial together.
One thing, the text is VERY soft which makes it difficult to read.

AtlantaTerry
Автор

WHich modulo result is correct mathematically? Using '%' or using fmod ?

sambitsuranjan
Автор

how to calculate modulus inverse without using function in python?

ebadhaider
Автор

1:14 Saving this for later because I know I'll forget

DeusKnight
Автор

r=13-(12*floor(13/12))... What's floor?

Besides lava...

GarethHUE