I need help understanding modulo and // in pyhthon… there doesnt means any sense to me//… 100 % 5 and 100 // 5

i need help understanding modulo and // in pyhthon… there doesnt means any sense to me//… 100 % 5 and 100 // 5

1 Like

This is code help, so it should have gone in that section, but I can still help. Modulo returns the remainder of the division, so a % b returns the remainder of a divided by b. // Is the floor division operator. This means it returns the greatest integer that is still less than the quotient. Thus a // b returns a/b rounded down.

4 Likes

Here’s quick explanation, although Thomas already said what it is.

// means floor division, so it’s just like / except it rounds the number down to the nearest integer, it’s important to note that it rounds down, so even if the number is something like 1.99 it will still output 1

The percent sign % returns the remainder, it’s often used to check if a number is even or odd

Some Examples:

Floor Division

x = 10 / 5
print(type(x)) # type is float

x = 10 // 5
print(type(x)) # type is int

Remainders

def is_even(number):
  if number % 2 == 0: # if the remainder is 0
    return True
  else:
    return False

is_even(21) # False
is_even(10) # True
4 Likes

@InvisibleOne gave an excellent reply. The only thing I could add is why to use integer divide.

Imagine that you have 85 people, and you want to know how many full soccer teams (11 people each) you can create.

85/11 = 7.727272727…

85//11 = 7

You could use the regular division and then int():

int(85/11) = 7

but the floor division is such a common thing to do that they have provided a shortcut.

3 Likes

Fantastic answers @ThomasWarenski @InvisibleOne and @gramie thank you!!

1 Like

It’s the least I can do after all the help Ask has given me with my own code. Gotta pay it forward.

5 Likes