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
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.
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
The percent sign
% returns the remainder, it’s often used to check if a number is even or odd
x = 10 / 5 print(type(x)) # type is float x = 10 // 5 print(type(x)) # type is int
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
@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.
Fantastic answers @ThomasWarenski @InvisibleOne and @gramie thank you!!
It’s the least I can do after all the help Ask has given me with my own code. Gotta pay it forward.