Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Modulo: Using the % Operator
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.
In this tutorial, you’ll learn:
- How modulo works in mathematics
- How to use the Python modulo operator with different numeric types
- How Python calculates the results of a modulo operation
- How to override
.__mod__()
in your classes to use them with the modulo operator - How to use the Python modulo operator to solve real-world problems
The Python modulo operator can sometimes be overlooked. But having a good understanding of this operator will give you an invaluable tool in your Python tool belt.
Modulo in Mathematics
The term modulo comes from a branch of mathematics called modular arithmetic. Modular arithmetic deals with integer arithmetic on a circular number line that has a fixed set of numbers. All arithmetic operations performed on this number line will wrap around when they reach a certain number called the modulus.
A classic example of modulo in modular arithmetic is the twelve-hour clock. A twelve-hour clock has a fixed set of values, from 1 to 12. When counting on a twelve-hour clock, you count up to the modulus 12 and then wrap back to 1. A twelve-hour clock can be classified as “modulo 12,” sometimes shortened to “mod 12.”
The modulo operator is used when you want to compare a number with the modulus and get the equivalent number constrained to the range of the modulus.
For example, say you want to determine what time it would be nine hours after 8:00 a.m. On a twelve-hour clock, you can’t simply add 9 to 8 because you would get 17. You need to take the result, 17, and use mod
to get its equivalent value in a twelve-hour context:
8 o'clock + 9 = 17 o'clock
17 mod 12 = 5
17 mod 12
returns 5
. This means that nine hours past 8:00 a.m. is 5:00 p.m. You determined this by taking the number 17
and applying it to a mod 12
context.
Now, if you think about it, 17
and 5
are equivalent in a mod 12
context. If you were to look at the hour hand at 5:00 and 17:00, it would be in the same position. Modular arithmetic has an equation to describe this relationship:
This equation reads “a
and b
are congruent modulo n
.” This means that a
and b
are equivalent in mod n
as they have the same remainder when divided by n
. In the above equation, n
is the modulus for both a
and b
. Using the values 17
and 5
from before, the equation would look like this:
This reads “17
and 5
are congruent modulo 12
.” 17
and 5
have the same remainder, 5
, when divided by 12
. So in mod 12
, the numbers 17
and 5
are equivalent.
You can confirm this using division:
17 / 12 = 1 R 5
5 / 12 = 0 R 5
Both of the operations have the same remainder, 5
, so they’re equivalent modulo 12
.
Now, this may seem like a lot of math for a Python operator, but having this knowledge will prepare you to use the modulo operator in the examples later in this tutorial. In the next section, you’ll look at the basics of using the Python modulo operator with the numeric types int
and float
.
Python Modulo Operator Basics
The modulo operator, like the other arithmetic operators, can be used with the numeric types int
and float
. As you’ll see later on, it can also be used with other types like math.fmod()
, decimal.Decimal
, and your own classes.
Modulo Operator With int
Most of the time you’ll use the modulo operator with integers. The modulo operator, when used with two positive integers, will return the remainder of standard Euclidean division:
>>>
>>> 15 % 4
3
>>> 17 % 12
5
>>> 240 % 13
6
>>> 10 % 16
10
Be careful! Just like with the division operator (/
), Python will return a ZeroDivisionError
if you try to use the modulo operator with a divisor of 0
:
>>>
>>> 22 % 0
ZeroDivisionError: integer division or modulo by zero
Next, you’ll take a look at using the modulo operator with a float
.
Modulo Operator With float
Similar to int
, the modulo operator used with a float
will return the remainder of division, but as a float
value:
>>>
>>> 12.5 % 5.5
1.5
>>> 17.0 % 12.0
5.0
An alternative to using a float
with the modulo operator is to use math.fmod()
to perform modulo operations on float
values:
>>>
>>> import math
>>> math.fmod(12.5, 5.5)
1.5
>>> math.fmod(8.5, 2.5)
1.0
The official Python docs suggest using math.fmod()
over the Python modulo operator when working with float
values because of the way math.fmod()
calculates the result of the modulo operation. If you’re using a negative operand, then you may see different results between math.fmod(x, y)
and x % y
. You’ll explore using the modulo operator with negative operands in more detail in the next section.
Just like other arithmetic operators, the modulo operator and math.fmod()
may encounter rounding and precision issues when dealing with floating-point arithmetic:
>>>
>>> 13.3 % 1.1
0.09999999999999964
>>> import math
>>> math.fmod(13.3, 1.1)
0.09999999999999964
If maintaining floating-point precision is important to your application, then you can use the modulo operator with decimal.Decimal
. You’ll look at this later in this tutorial.
Modulo Operator With a Negative Operand
All modulo operations you’ve seen up to this point have used two positive operands and returned predictable results. When a negative operand is introduced, things get more complicated.
As it turns out, the way that computers determine the result of a modulo operation with a negative operand leaves ambiguity as to whether the remainder should take the sign of the dividend (the number being divided) or the sign of the divisor (the number by which the dividend is divided). Different programming languages handle this differently.
For example, in JavaScript, the remainder will take the sign of the dividend:
The remainder in this example, 2
, is positive since it takes the sign of the dividend, 8
. In Python and other languages, the remainder will take the sign of the divisor instead:
Here you can see that the remainder, -1
, takes the sign of the divisor, -3
.
You may be wondering why the remainder in JavaScript is 2
and the remainder in Python is -1
. This has to do with how different languages determine the outcome of a modulo operation. Languages in which the remainder takes the sign of the dividend use the following equation to determine the remainder:
There are three variables this equation:
r
is the remainder.a
is the dividend.n
is the divisor.
trunc()
in this equation means that it uses truncated division, which will always round a negative number toward zero. For more clarification, see the steps of the modulo operation below using 8
as the dividend and -3
as the divisor:
r = 8 - (-3 * trunc(8/-3))
r = 8 - (-3 * trunc(-2.666666666667))
r = 8 - (-3 * -2) # Rounded toward 0
r = 8 - 6
r = 2
Here you can see how a language like JavaScript gets the remainder 2
. Python and other languages in which the remainder takes the sign of the divisor use the following equation:
floor()
in this equation means that it uses floor division. With positive numbers, floor division will return the same result as truncated division. But with a negative number, floor division will round the result down, away from zero:
r = 8 - (-3 * floor(8/-3))
r = 8 - (-3 * floor(-2.666666666667))
r = 8 - (-3 * -3) # Rounded away from 0
r = 8 - 9
r = -1
Here you can see that the result is -1
.
Now that you understand where the difference in the remainder comes from, you may be wondering why this matters if you only use Python. Well, as it turns out, not all modulo operations in Python are the same. While the modulo used with the int
and float
types will take the sign of the divisor, other types will not.
You can see an example of this when you compare the results of 8.0 % -3.0
and math.fmod(8.0, -3.0)
:
>>>
>>> 8.0 % -3
-1.0
>>> import math
>>> math.fmod(8.0, -3.0)
2.0
math.fmod()
takes the sign of the dividend using truncated division, whereas float
uses the sign of the divisor. Later in this tutorial, you’ll see another Python type that uses the sign of the dividend, decimal.Decimal
.
Modulo Operator and divmod()
Python has the built-in function divmod()
, which internally uses the modulo operator. divmod()
takes two parameters and returns a tuple containing the results of floor division and modulo using the supplied parameters.
Below is an example of using divmod()
with 37
and 5
:
>>>
>>> divmod(37, 5)
(7, 2)
>>> 37 // 5
7
>>> 37 % 5
2
You can see that divmod(37, 5)
returns the tuple (7, 2)
. The 7
is the result of the floor division of 37
and 5
. The 2
is the result of 37
modulo 5
.
Below is an example in which the second parameter is a negative number. As discussed in the previous section, when the modulo operator is used with an int
, the remainder will take the sign of the divisor:
>>>
>>> divmod(37, -5)
(-8, -3)
>>> 37 // -5
-8
>>> 37 % -5
-3 # Result has the sign of the divisor
Now that you’ve had a chance to see the modulo operator used in several scenarios, it’s important to take a look at how Python determines the precedence of the modulo operator when used with other arithmetic operators.
Modulo Operator Precedence
Like other Python operators, there are specific rules for the modulo operator that determine its precedence when evaluating expressions. The modulo operator (%
) shares the same level of precedence as the multiplication (*
), division (/
), and floor division (//
) operators.
Take a look at an example of the modulo operator’s precedence below:
>>>
>>> 4 * 10 % 12 - 9
-5
Both the multiplication and modulo operators have the same level of precedence, so Python will evaluate them from left to right. Here are the steps for the above operation:
4 * 10
is evaluated, resulting in40 % 12 - 9
.40 % 12
is evaluated, resulting in4 - 9
.4 - 9
is evaluated, resulting in-5
.
If you want to override the precedence of other operators, then you can use parentheses to surround the operation you want to be evaluated first:
>>>
>>> 4 * 10 % (12 - 9)
1
In this example, (12 - 9)
is evaluated first, followed by 4 * 10
and finally 40 % 3
, which equals 1
.
Python Modulo Operator in Practice
Now that you’ve gone through the basics of the Python modulo operator, you’ll look at some examples of using it to solve real-world programming problems. At times, it can be hard to determine when to use the modulo operator in your code. The examples below will give you an idea of the many ways it can be used.
How to Check if a Number Is Even or Odd
In this section, you’ll see how you can use the modulo operator to determine if a number is even or odd. Using the modulo operator with a modulus of 2
, you can check any number to see if it’s evenly divisible by 2
. If it is evenly divisible, then it’s an even number.
Take a look at is_even()
which checks to see if the num
parameter is even:
def is_even(num):
return num % 2 == 0
Here num % 2
will equal 0
if num
is even and 1
if num
is odd. Checking against 0
will return a Boolean of True
or False
based on whether or not num
is even.
Checking for odd numbers is quite similar. To check for an odd number, you invert the equality check:
def is_odd(num):
return num % 2 != 0
This function will return True
if num % 2
does not equal 0
, meaning that there’s a remainder proving num
is an odd number. Now, you may be wondering if you could use the following function to determine if num
is an odd number:
def is_odd(num):
return num % 2 == 1
The answer to this question is yes and no. Technically, this function will work with the way Python calculates modulo with integers. That said, you should avoid comparing the result of a modulo operation with 1
as not all modulo operations in Python will return the same remainder.
You can see why in the following examples:
>>>
>>> -3 % 2
1
>>> 3 % -2
-1
In the second example, the remainder takes the sign of the negative divisor and returns -1
. In this case, the Boolean check 3 % -2 == 1
would return False
.
However, if you compare the modulo operation with 0
, then it doesn’t matter which operand is negative. The result will always be True
when it’s an even number:
>>>
>>> -2 % 2
0
>>> 2 % -2
0
If you stick to comparing a Python modulo operation with 0
, then you shouldn’t have any problems checking for even and odd numbers or any other multiples of a number in your code.
In the next section, you’ll take a look at how you can use the modulo operator with loops to control the flow of your program.
How to Run Code at Specific Intervals in a Loop
With the Python modulo operator, you can run code at specific intervals inside a loop. This is done by performing a modulo operation with the current index of the loop and a modulus. The modulus number determines how often the interval-specific code will run in the loop.
Here’s an example:
def split_names_into_rows(name_list, modulus=3):
for index, name in enumerate(name_list, start=1):
print(f"{name:-^15} ", end="")
if index % modulus == 0:
print()
print()
This code defines split_names_into_rows()
, which takes two parameters. name_list
is a list of names that should be split into rows. modulus
sets a modulus for the operation, effectively determining how many names should be in each row. split_names_into_rows()
will loop over name_list
and start a new row after it hits the modulus
value.
Before breaking down the function in more detail, take a look at it in action:
>>>
>>> names = ["Picard", "Riker", "Troi", "Crusher", "Worf", "Data", "La Forge"]
>>> split_names_into_rows(names)
----Picard----- -----Riker----- -----Troi------
----Crusher---- -----Worf------ -----Data------
---La Forge----
As you can see, the list of names has been split into three rows, with a maximum of three names in each row. modulus
defaults to 3
, but you can specify any number:
>>>
>>> split_names_into_rows(names, modulus=4)
----Picard----- -----Riker----- -----Troi------ ----Crusher----
-----Worf------ -----Data------ ---La Forge----
>>> split_names_into_rows(names, modulus=2)
----Picard----- -----Riker-----
-----Troi------ ----Crusher----
-----Worf------ -----Data------
---La Forge----
>>> split_names_into_rows(names, modulus=1)
----Picard-----
-----Riker-----
-----Troi------
----Crusher----
-----Worf------
-----Data------
---La Forge----
Now that you’ve seen the code in action, you can break down what it’s doing. First, it uses enumerate()
to iterate over name_list
, assigning the current item in the list to name
and a count value to index
. You can see that the optional start
argument for enumerate()
is set to 1
. This means that the index
count will start at 1
instead of 0
:
for index, name in enumerate(name_list, start=1):
Next, inside the loop, the function calls print()
to output name
to the current row. The end
parameter for print()
is an empty string (""
) so it won’t output a newline at the end of the string. An f-string is passed to print()
, which uses the string output formatting syntax that Python provides:
print(f"{name:-^15} ", end="")
Without getting into too much detail, the :-^15
syntax tells print()
to do the following:
- Output at least
15
characters, even if the string is shorter than 15 characters. - Center align the string.
- Fill any space on the right or left of the string with the hyphen character (
-
).
Now that the name has been printed to the row, take a look at the main part of split_names_into_rows()
:
if index % modulus == 0:
print()
This code takes the current iteration index
and, using the modulo operator, compares it with modulus
. If the result equals 0
, then it can run interval-specific code. In this case, the function calls print()
to add a newline, which starts a new row.
The above code is only one example. Using the pattern index % modulus == 0
allows you to run different code at specific intervals in your loops. In the next section, you’ll take this concept a bit further and look at cyclic iteration.
How to Create Cyclic Iteration
Cyclic iteration describes a type of iteration that will reset once it gets to a certain point. Generally, this type of iteration is used to restrict the index of the iteration to a certain range.
You can use the modulo operator to create cyclic iteration. Take a look at an example using the turtle
library to draw a shape:
import turtle
import random
def draw_with_cyclic_iteration():
colors = ["green", "cyan", "orange", "purple", "red", "yellow", "white"]
turtle.bgcolor("gray8") # Hex: #333333
turtle.pendown()
turtle.pencolor(random.choice(colors)) # First color is random
i = 0 # Initial index
while True:
i = (i + 1) % 6 # Update the index
turtle.pensize(i) # Set pensize to i
turtle.forward(225)
turtle.right(170)
# Pick a random color
if i == 0:
turtle.pencolor(random.choice(colors))
The above code uses an infinite loop to draw a repeating star shape. After every six iterations, it changes the color of the pen. The pen size increases with each iteration until i
is reset back to 0
. If you run the code, then you should get something similar to this:
The important parts of this code are highlighted below:
import turtle
import random
def draw_with_cyclic_iteration():
colors = ["green", "cyan", "orange", "purple", "red", "yellow", "white"]
turtle.bgcolor("gray8") # Hex: #333333
turtle.pendown()
turtle.pencolor(random.choice(colors))
i = 0 # Initial index
while True:
i = (i + 1) % 6 # Update the index
turtle.pensize(i) # Set pensize to i
turtle.forward(225)
turtle.right(170)
# Pick a random color
if i == 0:
turtle.pencolor(random.choice(colors))
Each time through the loop, i
is updated based on the results of (i + 1) % 6
. This new i
value is used to increase the .pensize
with each iteration. Once i
reaches 5
, (i + 1) % 6
will equal 0
, and i
will reset back to 0
.
You can see the steps of the iteration below for more clarification:
i = 0 : (0 + 1) % 6 = 1
i = 1 : (1 + 1) % 6 = 2
i = 2 : (2 + 1) % 6 = 3
i = 3 : (3 + 1) % 6 = 4
i = 4 : (4 + 1) % 6 = 5
i = 5 : (5 + 1) % 6 = 0 # Reset
When i
is reset back to 0
, the .pencolor
changes to a new random color as seen below:
if i == 0:
turtle.pencolor(random.choice(colors))
The code in this section uses 6
as the modulus, but you could set it to any number to adjust how many times the loop will iterate before resetting the value i
.
How to Convert Units
In this section, you’ll look at how you can use the modulo operator to convert units. The following examples take smaller units and convert them into larger units without using decimals. The modulo operator is used to determine any remainder that may exist when the smaller unit isn’t evenly divisible by the larger unit.
In this first example, you’ll convert inches into feet. The modulo operator is used to get the remaining inches that don’t evenly divide into feet. The floor division operator (//
) is used to get the total feet rounded down:
def convert_inches_to_feet(total_inches):
inches = total_inches % 12
feet = total_inches // 12
print(f"{total_inches} inches = {feet} feet and {inches} inches")
Here’s an example of the function in use:
>>>
>>> convert_inches_to_feet(450)
450 inches = 37 feet and 6 inches
As you can see from the output, 450 % 12
returns 6
, which is the remaining inches that weren’t evenly divided into feet. The result of 450 // 12
is 37
, which is the total number of feet by which the inches were evenly divided.
You can take this a bit further in this next example. convert_minutes_to_days()
takes an integer, total_mins
, representing a number of minutes and outputs the period of time in days, hours, and minutes:
def convert_minutes_to_days(total_mins):
days = total_mins // 1440
extra_minutes = total_mins % 1440
hours = extra_minutes // 60
minutes = extra_minutes % 60
print(f"{total_mins} = {days} days, {hours} hours, and {minutes} minutes")
Breaking this down, you can see that the function does the following:
- Determines the total number of evenly divisible days with
total_mins // 1440
, where1440
is the number of minutes in a day - Calculates any
extra_minutes
left over withtotal_mins % 1440
- Uses the
extra_minutes
to get the evenly divisiblehours
and any extraminutes
You can see how it works below:
>>>
>>> convert_minutes_to_days(1503)
1503 = 1 days, 1 hours, and 3 minutes
>>> convert_minutes_to_days(3456)
3456 = 2 days, 9 hours, and 36 minutes
>>> convert_minutes_to_days(35000)
35000 = 24 days, 7 hours, and 20 minutes
While the above examples only deal with converting inches to feet and minutes to days, you could use any type of units with the modulo operator to convert a smaller unit into a larger unit.
Now that you’ve seen how to use the modulo operator to convert units, in the next section you’ll look at how you can use the modulo operator to check for prime numbers.
How to Determine if a Number Is a Prime Number
In this next example, you’ll take a look at how you can use the Python modulo operator to check whether a number is a prime number. A prime number is any number that contains only two factors, 1
and itself. Some examples of prime numbers are 2
, 3
, 5
, 7
, 23
, 29
, 59
, 83
, and 97
.
The code below is an implementation for determining the primality of a number using the modulo operator:
def check_prime_number(num):
if num < 2:
print(f"{num} must be greater than or equal to 2 to be prime.")
return
factors = [(1, num)]
i = 2
while i * i <= num:
if num % i == 0:
factors.append((i, num//i))
i += 1
if len(factors) > 1:
print(f"{num} is not prime. It has the following factors: {factors}")
else:
print(f"{num} is a prime number")
This code defines check_prime_number()
, which takes the parameter num
and checks to see if it’s a prime number. If it is, then a message is displayed stating that num
is a prime number. If it’s not a prime number, then a message is displayed with all the factors of the number.
Before you look more closely at the function, here are the results using some different numbers:
>>>
>>> check_prime_number(44)
44 is not prime. It has the following factors: [(1, 44), (2, 22), (4, 11)]
>>> check_prime_number(53)
53 is a prime number
>>> check_prime_number(115)
115 is not prime. It has the following factors: [(1, 115), (5, 23)]
>>> check_prime_number(997)
997 is a prime number
Digging into the code, you can see it starts by checking if num
is less than 2
. Prime numbers can only be greater than or equal to 2
. If num
is less than 2
, then the function doesn’t need to continue. It will print()
a message and return
:
if num < 2:
print(f"{num} must be greater than or equal to 2 to be prime.")
return
If num
is greater than 2
, then the function checks if num
is a prime number. To check this, the function iterates over all the numbers between 2
and the square root of num
to see if any divide evenly into num
. If one of the numbers divides evenly, then a factor has been found, and num
can’t be a prime number.
Here’s the main part of the function:
factors = [(1, num)]
i = 2
while i * i <= num:
if num % i == 0:
factors.append((i, num//i))
i += 1
There’s a lot to unpack here, so let’s take it step by step.
First, a factors
list is created with the initial factors, (1, num)
. This list will be used to store any other factors that are found:
Next, starting with 2
, the code increments i
until it reaches the square root of num
. At each iteration, it compares num
with i
to see if it’s evenly divisible. The code only needs to check up to and including the square root of num
because it wouldn’t contain any factors above this:
i = 2
while i * i <= num:
if num % i == 0:
factors.append((i, num//i))
i += 1
Instead of trying to determine the square root of num
, the function uses a while
loop to see if i * i <= num
. As long as i * i <= num
, the loop hasn’t reached the square root of num
.
Inside the while
loop, the modulo operator checks if num
is evenly divisible by i
:
factors = [(1, num)]
i = 2 # Start the initial index at 2
while i * i <= num:
if num % i == 0:
factors.append((i, num//i))
i += 1
If num
is evenly divisible by i
, then i
is a factor of num
, and a tuple of the factors is added to the factors
list.
Once the while
loop is complete, the code checks to see if any additional factors were found:
if len(factors) > 1:
print(f"{num} is not prime. It has the following factors: {factors}")
else:
print(f"{num} is a prime number")
If more than one tuple exists in the factors
list, then num
can’t be a prime number. For nonprime numbers, the factors are printed out. For prime numbers, the function prints a message stating that num
is a prime number.
How to Implement Ciphers
The Python modulo operator can be used to create ciphers. A cipher is a type of algorithm for performing encryption and decryption on an input, usually text. In this section, you’ll look at two ciphers, the Caesar cipher and the Vigenère cipher.
Caesar Cipher
The first cipher that you’ll look at is the Caesar cipher, named after Julius Caesar, who used it to secretly communicate messages. It’s a substitution cipher that uses letter substitution to encrypt a string of text.
The Caesar cipher works by taking a letter to be encrypted and shifting it a certain number of positions to the left or right in the alphabet. Whichever letter is in that position is used as the encrypted character. This same shift value is applied to all characters in the string.
For example, if the shift were 5
, then A
would shift up five letters to become F
, B
would become G
, and so on. Below you can see the encryption process for the text REALPYTHON
with a shift of 5
:
The resulting cipher is WJFQUDYMTS
.
Decrypting the cipher is done by reversing the shift. Both the encryption and decryption processes can be described with the following expressions, where char_index
is the index of the character in the alphabet:
encrypted_char_index = (char_index + shift) % 26
decrypted_char_index = (char_index - shift) % 26
This cipher uses the modulo operator to make sure that, when shifting a letter, the index will wrap around if the end of the alphabet is reached. Now that you know how this cipher works, take a look at an implementation:
import string
def caesar_cipher(text, shift, decrypt=False):
if not text.isascii() or not text.isalpha():
raise ValueError("Text must be ASCII and contain no numbers.")
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
result = ""
if decrypt:
shift = shift * -1
for char in text:
if char.islower():
index = lowercase.index(char)
result += lowercase[(index + shift) % 26]
else:
index = uppercase.index(char)
result += uppercase[(index + shift) % 26]
return result
This code defines a function called caesar_cipher()
, which has two required parameters and one optional parameter:
text
is the text to be encrypted or decrypted.shift
is the number of positions to shift each letter.decrypt
is a Boolean to set iftext
should be decrypted.
decrypt
is included so that a single function can be used to handle both encryption and decryption. This implementation can handle only alphabetic characters, so the function first checks that text
is an alphabetic character in the ASCII encoding:
def caesar_cipher(text, shift, decrypt=False):
if not text.isascii() or not text.isalpha():
raise ValueError("Text must be ASCII and contain no numbers.")
The function then defines three variables to store the lowercase
ASCII characters, the uppercase
ASCII characters, and the results of the encryption or decryption:
lowercase = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz"
uppercase = string.ascii_uppercase # "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ""
Next, if the function is being used to decrypt text
, then it multiplies shift
by -1
to make it shift backward:
if decrypt:
shift = shift * -1
Finally, caesar_cipher()
loops over the individual characters in text
and performs the following actions for each char
:
- Check if
char
is lowercase or uppercase. - Get the
index
of thechar
in either thelowercase
oruppercase
ASCII lists. - Add a
shift
to thisindex
to determine the index of the cipher character to use. - Use
% 26
to make sure the shift will wrap back to the start of the alphabet. - Append the cipher character to the
result
string.
After the loop finishes iterating over the text
value, the result
is returned:
for char in text:
if char.islower():
index = lowercase.index(char)
result += lowercase[(index + shift) % 26]
else:
index = uppercase.index(char)
result += uppercase[(index + shift) % 26]
return result
Here’s the full code again:
import string
def caesar_cipher(text, shift, decrypt=False):
if not text.isascii() or not text.isalpha():
raise ValueError("Text must be ASCII and contain no numbers.")
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
result = ""
if decrypt:
shift = shift * -1
for char in text:
if char.islower():
index = lowercase.index(char)
result += lowercase[(index + shift) % 26]
else:
index = uppercase.index(char)
result += uppercase[(index + shift) % 26]
return result
Now run the code in the Python REPL using the text meetMeAtOurHideOutAtTwo
with a shift of 10
:
>>>
>>> caesar_cipher("meetMeAtOurHideOutAtTwo", 10)
woodWoKdYebRsnoYedKdDgy
The encrypted result is woodWoKdYebRsnoYedKdDgy
. Using this encrypted text, you can run the decryption to get the original text:
>>>
>>> caesar_cipher("woodWoKdYebRsnoYedKdDgy", 10, decrypt=True)
meetMeAtOurHideOutAtTwo
The Caesar cipher is fun to play around with for an introduction to cryptography. While the Caesar cipher is rarely used on its own, it’s the basis for more complex substitution ciphers. In the next section, you’ll look at one of the Caesar cipher’s descendants, the Vigenère cipher.
Vigenère Cipher
The Vigenère cipher is a polyalphabetic substitution cipher. To perform its encryption, it employs a different Caesar cipher for each letter of the input text. The Vigenère cipher uses a keyword to determine which Caesar cipher should be used to find the cipher letter.
You can see an example of the encryption process in the following image. In this example, the input text REALPYTHON
is encrypted using the keyword MODULO
:
For each letter of the input text, REALPYTHON
, a letter from the keyword MODULO
is used to determine which Caesar cipher column should be selected. If the keyword is shorter than the input text, as is the case with MODULO
, then the letters of the keyword are repeated until all letters of the input text have been encrypted.
Below is an implementation of the Vigenère cipher. As you’ll see, the modulo operator is used twice in the function:
import string
def vigenere_cipher(text, key, decrypt=False):
if not text.isascii() or not text.isalpha() or not text.isupper():
raise ValueError("Text must be uppercase ASCII without numbers.")
uppercase = string.ascii_uppercase # "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
results = ""
for i, char in enumerate(text):
current_key = key[i % len(key)]
char_index = uppercase.index(char)
key_index = uppercase.index(current_key)
if decrypt:
index = char_index - key_index + 26
else:
index = char_index + key_index
results += uppercase[index % 26]
return results
You may have noticed that the signature for vigenere_cipher()
is quite similar to caesar_cipher()
from the previous section:
def vigenere_cipher(text, key, decrypt=False):
if not text.isascii() or not text.isalpha() or not text.isupper():
raise ValueError("Text must be uppercase ASCII without numbers.")
uppercase = string.ascii_uppercase
results = ""
The main difference is that, instead of a shift
parameter, vigenere_cipher()
takes a key
parameter, which is the keyword to be used during encryption and decryption. Another difference is the addition of text.isupper()
. Based on this implementation, vigenere_cipher()
can only accept input text that is all uppercase.
Like caesar_cipher()
, vigenere_cipher()
iterates over each letter of the input text to encrypt or decrypt it:
for i, char in enumerate(text):
current_key = key[i % len(key)]
In the above code, you can see the function’s first use of the modulo operator:
current_key = key[i % len(key)]
Here, the current_key
value is determined based on an index returned from i % len(key)
. This index is used to select a letter from the key
string, such as M
from MODULO
.
The modulo operator allows you to use any length keyword regardless of the length of the text
to be encrypted. Once the index i
, the index of the character currently being encrypted, equals the length of the keyword, it will start over from the beginning of the keyword.
For each letter of the input text, several steps determine how to encrypt or decrypt it:
- Determine the
char_index
based on the index ofchar
insideuppercase
. - Determine the
key_index
based on the index ofcurrent_key
insideuppercase
. - Use
char_index
andkey_index
to get the index for the encrypted or decrypted character.
Take a look at these steps in the code below:
char_index = uppercase.index(char)
key_index = uppercase.index(current_key)
if decrypt:
index = char_index - key_index + 26
else:
index = char_index + key_index
You can see that the indices for decryption and encryption are calculated differently. That’s why decrypt
is used in this function. This way, you can use the function for both encryption and decryption.
After the index
is determined, you find the function’s second use of the modulo operator:
results += uppercase[index % 26]
index % 26
ensures that the index
of the character doesn’t exceed 25
, thus making sure it stays inside the alphabet. With this index, the encrypted or decrypted character is selected from uppercase
and appended to results
.
Here’s the full code the Vigenère cipher again:
import string
def vigenere_cipher(text, key, decrypt=False):
if not text.isascii() or not text.isalpha() or not text.isupper():
raise ValueError("Text must be uppercase ASCII without numbers.")
uppercase = string.ascii_uppercase # "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
results = ""
for i, char in enumerate(text):
current_key = key[i % len(key)]
char_index = uppercase.index(char)
key_index = uppercase.index(current_key)
if decrypt:
index = char_index - key_index + 26
else:
index = char_index + key_index
results += uppercase[index % 26]
return results
Now go ahead and run it in the Python REPL:
>>>
>>> vigenere_cipher(text="REALPYTHON", key="MODULO")
DSDFAMFVRH
>>> encrypted = vigenere_cipher(text="REALPYTHON", key="MODULO")
>>> print(encrypted)
DSDFAMFVRH
>>> vigenere_cipher(encrypted, "MODULO", decrypt=True)
REALPYTHON
Nice! You now have a working Vigenère cipher for encrypting text strings.
Python Modulo Operator Advanced Uses
In this final section, you’ll take your modulo operator knowledge to the next level by using it with decimal.Decimal
. You’ll also look at how you can add .__mod__()
to your custom classes so they can be used with the modulo operator.
Using the Python Modulo Operator With decimal.Decimal
Earlier in this tutorial, you saw how you can use the modulo operator with numeric types like int
and float
as well as with math.fmod()
. You can also use the modulo operator with Decimal
from the decimal
module. You use decimal.Decimal
when you want discrete control of the precision of floating-point arithmetic operations.
Here are some examples of using whole integers with decimal.Decimal
and the modulo operator:
>>>
>>> import decimal
>>> decimal.Decimal(15) % decimal.Decimal(4)
Decimal('3')
>>> decimal.Decimal(240) % decimal.Decimal(13)
Decimal('6')
Here are some floating-point numbers used with decimal.Decimal
and the modulo operator:
>>>
>>> decimal.Decimal("12.5") % decimal.Decimal("5.5")
Decimal('1.5')
>>> decimal.Decimal("13.3") % decimal.Decimal("1.1")
Decimal('0.1')
All modulo operations with decimal.Decimal
return the same results as other numeric types, except when one of the operands is negative. Unlike int
and float
, but like math.fmod()
, decimal.Decimal
uses the sign of the dividend for the results.
Take a look at the examples below comparing the results of using the modulo operator with standard int
and float
values and with decimal.Decimal
:
>>>
>>> -17 % 3
1 # Sign of the divisor
>>> decimal.Decimal(-17) % decimal.Decimal(3)
Decimal(-2) # Sign of the dividend
>>> 17 % -3
-1 # Sign of the divisor
>>> decimal.Decimal(17) % decimal.Decimal(-3)
Decimal("2") # Sign of dividend
>>> -13.3 % 1.1
1.0000000000000004 # Sign of the divisor
>>> decimal.Decimal("-13.3") % decimal.Decimal("1.1")
Decimal("-0.1") # Sign of the dividend
Compared with math.fmod()
, decimal.Decimal
will have the same sign, but the precision will be different:
>>>
>>> decimal.Decimal("-13.3") % decimal.Decimal("1.1")
Decimal("-0.1")
>>> math.fmod(-13.3, 1.1)
-0.09999999999999964
As you can see from the above examples, working with decimal.Decimal
and the modulo operator is similar to working with other numeric types. You just need to keep in mind how it determines the sign of the result when working with a negative operand.
In the next section, you’ll look at how you can override the modulo operator in your classes to customize its behavior.
Using the Python Modulo Operator With Custom Classes
The Python data model allows to you override the built-in methods in a Python object to customize its behavior. In this section, you’ll look at how to override .__mod__()
so that you can use the modulo operator with your own classes.
For this example, you’ll be working with a Student
class. This class will track the amount of time a student has studied. Here’s the initial Student
class:
class Student:
def __init__(self, name):
self.name = name
self.study_sessions = []
def add_study_sessions(self, sessions):
self.study_sessions += sessions
The Student
class is initialized with a name
parameter and starts with an empty list, study_sessions
, which will hold a list of integers representing minutes studied per session. There’s also .add_study_sessions()
, which takes a sessions
parameter that should be a list of study sessions to add to study_sessions
.
Now, if you remember from the converting units section above, convert_minutes_to_day()
used the Python modulo operator to convert total_mins
into days, hours, and minutes. You’ll now implement a modified version of that method to see how you can use your custom class with the modulo operator:
def total_study_time_in_hours(student, total_mins):
hours = total_mins // 60
minutes = total_mins % 60
print(f"{student.name} studied {hours} hours and {minutes} minutes")
You can use this function with the Student
class to display the total hours a Student
has studied. Combined with the Student
class above, the code will look like this:
class Student:
def __init__(self, name):
self.name = name
self.study_sessions = []
def add_study_sessions(self, sessions):
self.study_sessions += sessions
def total_study_time_in_hours(student, total_mins):
hours = total_mins // 60
minutes = total_mins % 60
print(f"{student.name} studied {hours} hours and {minutes} minutes")
If you load this module in the Python REPL, then you can use it like this:
>>>
>>> jane = Student("Jane")
>>> jane.add_study_sessions([120, 30, 56, 260, 130, 25, 75])
>>> total_mins = sum(jane.study_sessions)
>>> total_study_time_in_hours(jane, total_mins)
Jane studied 11 hours and 36 minutes
The above code prints out the total hours jane
studied. This version of the code works, but it requires the extra step of summing study_sessions
to get total_mins
before calling total_study_time_in_hours()
.
Here’s how you can modify the Student
class to simplify the code:
class Student:
def __init__(self, name):
self.name = name
self.study_sessions = []
def add_study_sessions(self, sessions):
self.study_sessions += sessions
def __mod__(self, other):
return sum(self.study_sessions) % other
def __floordiv__(self, other):
return sum(self.study_sessions) // other
By overriding .__mod__()
and .__floordiv__()
, you can use a Student
instance with the modulo operator. Calculating the sum()
of study_sessions
is included in the Student
class as well.
With these modifications, you can use a Student
instance directly in total_study_time_in_hours()
. As total_mins
is no longer needed, you can remove it:
def total_study_time_in_hours(student):
hours = student // 60
minutes = student % 60
print(f"{student.name} studied {hours} hours and {minutes} minutes")
Here’s the full code after modifications:
class Student:
def __init__(self, name):
self.name = name
self.study_sessions = []
def add_study_sessions(self, sessions):
self.study_sessions += sessions
def __mod__(self, other):
return sum(self.study_sessions) % other
def __floordiv__(self, other):
return sum(self.study_sessions) // other
def total_study_time_in_hours(student):
hours = student // 60
minutes = student % 60
print(f"{student.name} studied {hours} hours and {minutes} minutes")
Now, calling the code in the Python REPL, you can see it’s much more succinct:
>>>
>>> jane = Student("Jane")
>>> jane.add_study_sessions([120, 30, 56, 260, 130, 25, 75])
>>> total_study_time_in_hours(jane)
Jane studied 11 hours and 36 minutes
By overriding .__mod__()
, you allow your custom classes to behave more like Python’s built-in numeric types.
Conclusion
At first glance, the Python modulo operator may not grab your attention. Yet, as you’ve seen, there’s so much to this humble operator. From checking for even numbers to encrypting text with ciphers, you’ve seen many different uses for the modulo operator.
In this tutorial, you’ve learned how to:
- Use the modulo operator with
int
,float
,math.fmod()
,divmod()
, anddecimal.Decimal
- Calculate the results of a modulo operation
- Solve real-world problems using the modulo operator
- Override
.__mod__()
in your own classes to use them with the modulo operator
With the knowledge you’ve gained in this tutorial, you can now start using the modulo operator in your own code with great success. Happy Pythoning!
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Modulo: Using the % Operator
This module is always available. It provides access to the mathematical
functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions of the
same name from the cmath
module if you require support for complex
numbers. The distinction between functions which support complex numbers and
those which don’t is made since most users do not want to learn quite as much
mathematics as required to understand complex numbers. Receiving an exception
instead of a complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how and why it
was generated in the first place.
The following functions are provided by this module. Except when explicitly
noted otherwise, all return values are floats.
9.2.1. Number-theoretic and representation functions¶
-
math.
ceil
(x)¶ -
Return the ceiling of x, the smallest integer greater than or equal to x.
If x is not a float, delegates tox.__ceil__()
, which should return an
Integral
value.
-
math.
copysign
(x, y)¶ -
Return a float with the magnitude (absolute value) of x but the sign of
y. On platforms that support signed zeros,copysign(1.0, -0.0)
returns -1.0.
-
math.
fabs
(x)¶ -
Return the absolute value of x.
-
math.
factorial
(x)¶ -
Return x factorial. Raises
ValueError
if x is not integral or
is negative.
-
math.
floor
(x)¶ -
Return the floor of x, the largest integer less than or equal to x.
If x is not a float, delegates tox.__floor__()
, which should return an
Integral
value.
-
math.
fmod
(x, y)¶ -
Return
fmod(x, y)
, as defined by the platform C library. Note that the
Python expressionx % y
may not return the same result. The intent of the C
standard is thatfmod(x, y)
be exactly (mathematically; to infinite
precision) equal tox - n*y
for some integer n such that the result has
the same sign as x and magnitude less thanabs(y)
. Python’sx % y
returns a result with the sign of y instead, and may not be exactly computable
for float arguments. For example,fmod(-1e-100, 1e100)
is-1e-100
, but
the result of Python’s-1e-100 % 1e100
is1e100-1e-100
, which cannot be
represented exactly as a float, and rounds to the surprising1e100
. For
this reason, functionfmod()
is generally preferred when working with
floats, while Python’sx % y
is preferred when working with integers.
-
math.
frexp
(x)¶ -
Return the mantissa and exponent of x as the pair
(m, e)
. m is a float
and e is an integer such thatx == m * 2**e
exactly. If x is zero,
returns(0.0, 0)
, otherwise0.5 <= abs(m) < 1
. This is used to “pick
apart” the internal representation of a float in a portable way.
-
math.
fsum
(iterable)¶ -
Return an accurate floating point sum of values in the iterable. Avoids
loss of precision by tracking multiple intermediate partial sums:>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the
typical case where the rounding mode is half-even. On some non-Windows
builds, the underlying C library uses extended precision addition and may
occasionally double-round an intermediate sum causing it to be off in its
least significant bit.For further discussion and two alternative approaches, see the ASPN cookbook
recipes for accurate floating point summation.
-
math.
gcd
(a, b)¶ -
Return the greatest common divisor of the integers a and b. If either
a or b is nonzero, then the value ofgcd(a, b)
is the largest
positive integer that divides both a and b.gcd(0, 0)
returns
0
.New in version 3.5.
-
math.
isclose
(a, b, *, rel_tol=1e-09, abs_tol=0.0)¶ -
Return
True
if the values a and b are close to each other and
False
otherwise.Whether or not two values are considered close is determined according to
given absolute and relative tolerances.rel_tol is the relative tolerance – it is the maximum allowed difference
between a and b, relative to the larger absolute value of a or b.
For example, to set a tolerance of 5%, passrel_tol=0.05
. The default
tolerance is1e-09
, which assures that the two values are the same
within about 9 decimal digits. rel_tol must be greater than zero.abs_tol is the minimum absolute tolerance – useful for comparisons near
zero. abs_tol must be at least zero.If no errors occur, the result will be:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
.The IEEE 754 special values of
NaN
,inf
, and-inf
will be
handled according to IEEE rules. Specifically,NaN
is not considered
close to any other value, includingNaN
.inf
and-inf
are only
considered close to themselves.New in version 3.5.
See also
PEP 485 – A function for testing approximate equality
-
math.
isfinite
(x)¶ -
Return
True
if x is neither an infinity nor a NaN, and
False
otherwise. (Note that0.0
is considered finite.)New in version 3.2.
-
math.
isinf
(x)¶ -
Return
True
if x is a positive or negative infinity, and
False
otherwise.
-
math.
isnan
(x)¶ -
Return
True
if x is a NaN (not a number), andFalse
otherwise.
-
math.
ldexp
(x, i)¶ -
Return
x * (2**i)
. This is essentially the inverse of function
frexp()
.
-
math.
modf
(x)¶ -
Return the fractional and integer parts of x. Both results carry the sign
of x and are floats.
-
math.
trunc
(x)¶ -
Return the
Real
value x truncated to an
Integral
(usually an integer). Delegates to
x.__trunc__()
.
Note that frexp()
and modf()
have a different call/return pattern
than their C equivalents: they take a single argument and return a pair of
values, rather than returning their second return value through an ‘output
parameter’ (there is no such thing in Python).
For the ceil()
, floor()
, and modf()
functions, note that all
floating-point numbers of sufficiently large magnitude are exact integers.
Python floats typically carry no more than 53 bits of precision (the same as the
platform C double type), in which case any float x with abs(x) >= 2**52
necessarily has no fractional bits.
9.2.2. Power and logarithmic functions¶
-
math.
exp
(x)¶ -
Return
e**x
.
-
math.
expm1
(x)¶ -
Return
e**x - 1
. For small floats x, the subtraction inexp(x) - 1
can result in a significant loss of precision; theexpm1()
function provides a way to compute this quantity to full precision:>>> from math import exp, expm1 >>> exp(1e-5) - 1 # gives result accurate to 11 places 1.0000050000069649e-05 >>> expm1(1e-5) # result accurate to full precision 1.0000050000166668e-05
New in version 3.2.
-
math.
log
(x[, base])¶ -
With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base,
calculated aslog(x)/log(base)
.
-
math.
log1p
(x)¶ -
Return the natural logarithm of 1+x (base e). The
result is calculated in a way which is accurate for x near zero.
-
math.
log2
(x)¶ -
Return the base-2 logarithm of x. This is usually more accurate than
log(x, 2)
.New in version 3.3.
See also
int.bit_length()
returns the number of bits necessary to represent
an integer in binary, excluding the sign and leading zeros.
-
math.
log10
(x)¶ -
Return the base-10 logarithm of x. This is usually more accurate
thanlog(x, 10)
.
-
math.
pow
(x, y)¶ -
Return
x
raised to the powery
. Exceptional cases follow
Annex ‘F’ of the C99 standard as far as possible. In particular,
pow(1.0, x)
andpow(x, 0.0)
always return1.0
, even
whenx
is a zero or a NaN. If bothx
andy
are finite,
x
is negative, andy
is not an integer thenpow(x, y)
is undefined, and raisesValueError
.Unlike the built-in
**
operator,math.pow()
converts both
its arguments to typefloat
. Use**
or the built-in
pow()
function for computing exact integer powers.
-
math.
sqrt
(x)¶ -
Return the square root of x.
9.2.3. Trigonometric functions¶
-
math.
acos
(x)¶ -
Return the arc cosine of x, in radians.
-
math.
asin
(x)¶ -
Return the arc sine of x, in radians.
-
math.
atan
(x)¶ -
Return the arc tangent of x, in radians.
-
math.
atan2
(y, x)¶ -
Return
atan(y / x)
, in radians. The result is between-pi
andpi
.
The vector in the plane from the origin to point(x, y)
makes this angle
with the positive X axis. The point ofatan2()
is that the signs of both
inputs are known to it, so it can compute the correct quadrant for the angle.
For example,atan(1)
andatan2(1, 1)
are bothpi/4
, butatan2(-1,
is
-1)-3*pi/4
.
-
math.
cos
(x)¶ -
Return the cosine of x radians.
-
math.
hypot
(x, y)¶ -
Return the Euclidean norm,
sqrt(x*x + y*y)
. This is the length of the vector
from the origin to point(x, y)
.
-
math.
sin
(x)¶ -
Return the sine of x radians.
-
math.
tan
(x)¶ -
Return the tangent of x radians.
9.2.4. Angular conversion¶
-
math.
degrees
(x)¶ -
Convert angle x from radians to degrees.
-
math.
radians
(x)¶ -
Convert angle x from degrees to radians.
9.2.5. Hyperbolic functions¶
Hyperbolic functions
are analogs of trigonometric functions that are based on hyperbolas
instead of circles.
-
math.
acosh
(x)¶ -
Return the inverse hyperbolic cosine of x.
-
math.
asinh
(x)¶ -
Return the inverse hyperbolic sine of x.
-
math.
atanh
(x)¶ -
Return the inverse hyperbolic tangent of x.
-
math.
cosh
(x)¶ -
Return the hyperbolic cosine of x.
-
math.
sinh
(x)¶ -
Return the hyperbolic sine of x.
-
math.
tanh
(x)¶ -
Return the hyperbolic tangent of x.
9.2.6. Special functions¶
-
math.
erf
(x)¶ -
Return the error function at
x.The
erf()
function can be used to compute traditional statistical
functions such as the cumulative standard normal distribution:def phi(x): 'Cumulative distribution function for the standard normal distribution' return (1.0 + erf(x / sqrt(2.0))) / 2.0
New in version 3.2.
-
math.
erfc
(x)¶ -
Return the complementary error function at x. The complementary error
function is defined as
1.0 - erf(x)
. It is used for large values of x where a subtraction
from one would cause a loss of significance.New in version 3.2.
-
math.
gamma
(x)¶ -
Return the Gamma function at
x.New in version 3.2.
-
math.
lgamma
(x)¶ -
Return the natural logarithm of the absolute value of the Gamma
function at x.New in version 3.2.
9.2.7. Constants¶
-
math.
pi
¶ -
The mathematical constant π = 3.141592…, to available precision.
-
math.
e
¶ -
The mathematical constant e = 2.718281…, to available precision.
-
math.
tau
¶ -
The mathematical constant τ = 6.283185…, to available precision.
Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to
its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still)
Wrong, and start celebrating
Tau day by eating twice as much pie!New in version 3.6.
-
math.
inf
¶ -
A floating-point positive infinity. (For negative infinity, use
-math.inf
.) Equivalent to the output offloat('inf')
.New in version 3.5.
-
math.
nan
¶ -
A floating-point “not a number” (NaN) value. Equivalent to the output of
float('nan')
.New in version 3.5.
CPython implementation detail: The math
module consists mostly of thin wrappers around the platform C
math library functions. Behavior in exceptional cases follows Annex F of
the C99 standard where appropriate. The current implementation will raise
ValueError
for invalid operations like sqrt(-1.0)
or log(0.0)
(where C99 Annex F recommends signaling invalid operation or divide-by-zero),
and OverflowError
for results that overflow (for example,
exp(1000.0)
). A NaN will not be returned from any of the functions
above unless one or more of the input arguments was a NaN; in that case,
most functions will return a NaN, but (again following C99 Annex F) there
are some exceptions to this rule, for example pow(float('nan'), 0.0)
or
hypot(float('nan'), float('inf'))
.
Note that Python makes no effort to distinguish signaling NaNs from
quiet NaNs, and behavior for signaling NaNs remains unspecified.
Typical behavior is to treat all NaNs as though they were quiet.
See also
- Module
cmath
- Complex number versions of many of these functions.
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
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.
Modulo Operator with Integer
Stores the remainder obtained when dividing a by b, in c
Python3
a
=
13
b
=
5
c
=
a
%
b
print
(a,
"mod"
, b,
"="
,
c, sep
=
" "
)
Output:
13 mod 5 = 3
Modulo Operator With float with a negative number.
Stores the remainder obtained when dividing d by e, in f. For more examples, refer to How to Perform Modulo with Negative Values in Python.
Python3
d
=
15.0
e
=
-
7.0
f
=
d
%
e
print
(d,
"mod"
, e,
"="
,
f, sep
=
" "
)
Output:
15.0 mod -7.0 = -6.0
Example using the Modulo Operator
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 :
25 May, 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 вместе с вами, читаю, собираю и записываю информацию опытных программистов.