Saturday, May 9, 2015

Modulo Operator to Get Remainder In Python - Python Numbers - Python Tutorial

Modulo Operator to Get Remainder In PythonModulo Operator to Get Remainder In Python


In this Python tutorial we are going to focus on Modulo Operator to Get Remainder In Python.  We could use modulo to get remainder after division is performed.  This can be a little confusing at times so make sure you check work closely to make sure your program is performing as expected.


How Modulo Operator Works


To implement the modulo operator we need to use the percent sign(%) in our equations. When use the percent sign in an equation we will get the remainder after division is performed. Sometimes this will return a number that does not make much sense so we will look at that as well.


Modulo Examples


In this tutorial all the examples will be carried out in the Python interpreter. We suggest you open your Python interpreter and follow a long. Practicing modulos will help you figure out how it actually works.


#Modulo Examples

#No remainder when you divide 8 by 2
>>> 8 % 2
0

#10 divided by 3 is 9 with 1 left over
>>> 10 % 3
1

#12.5 divided by 5 is 2.5
>>> 12.5 % 5
2.5


Now the Confusing Modulo Equations


This may or may not be confusing to you, but I remember when I first learned how to use modulo this was a bit confusing to me a times until I figured out what was going on.


#Now the Confusing Modulo Equations

#What is going on here?
#When you use modulo here where numbers go in evenly it will return the exact number of the modulo number
>>> 25 % 50
25


#This is also the proper remainder
>>> 30 % 70
30

In the above example what is going on? Well we can not divide a smaller number by a larger number.  Think of this way if you have a job to go out and get 70 beers and not to return till you got these 70 beers going to a store with only 30 is not going to cut it so when you leave that store the store still has 30 beers. This is the best way I can explain it.

In this tutorial, we looked at Modulo Operator to Get Remainder In Python which is a useful tool to find the remaining numbers. If you have any questions please leave a comment below.



No comments:

Post a Comment