Mod operator in Python

The Modulus operator

The mod operator gives you the reminder you get by dividing the first number with the second number:

5 % 3 (Five mod Three)

Output: 2

This is asking what the remainder you get when you divide five by three...

x mod y = r
x (dividend)
y (divisor)
r (remainder)
2

The math is this:


  1.  5 / 3 = 1.66
  2. Round that down = 1
  3. 1 * 3 = 3
  4. The difference between 5 and 3 = 2 


A remainder in mathematics is what's left over in a division problem. When you divide the number you divide up is calle dthe Dividend. The number you are dividiing by is called the Divisor.

The number has to be Integer

Example with a function:

print('Mod operator in Python...')
print(5 % 3)

def count_events(nums):
       count = 0
       for x in nums:
           if x % 2 == 0:
               count += 1
       return count


print(count_events([2,3,1,3,1,3,3,1,7,23,8]))

Output: 2


Comments

Popular posts from this blog

Installing Microsoft ODBC Driver to connect to SQL from Python on Mac OS X

Connection to MSSQL with Pythonan and pyodbc (on Mac OS X)

Installing PyCharm on Mac