Python modulo question

Hello I’m learning Python 3 to get a head start when I start my college course next week. I have a question about the modulo operator. Why does print(8%9) or any number greater than 9 result in 8 being output to the console?

That’s how modulo is designed to work, it gives you the remainder of your division- Modulo operation - Wikipedia

Since 8 modulo anything greater than 8 will have a quotient of 0 all you have is the remainder. Much like 1 modulo (anything greater than 1.0) will always return 1.

I don’t understand how 8 is the remainder from this equation, I guess that’s what my question is. The way I’m trying to understand it is: 8/9=0.888888888888 then 8%9=?
I don’t understand how 8 is the remainder when 0.88888888888 is not a whole number.
I mean I know the numbers are the wrong way around but this is still something I want to understand.
9/8 = 1 (9//8 to be precise)
9%8 = 1
I get this bit :slight_smile:

It would be worth looking up quotient and reminader the wikipedia link should have redirections to this if you like.

What you’re relying on here is integer division. So we use whole numbers.

1 divided by 5 would be a quotient of 0 and a remainder of 1
5 divided by 5 would be a quotient of 1 and a remainder of 0
7 divided by 5 would be a quotient of 1 and a remainder of 2

All modulo gives you is the remainder of this calculation.

2 Likes

I think I’ve found the reason.
8/9=0.888888888
8//9=0
8%9=8
I think it returns 8 because 9 cant go into 8 so as in 8//9 it returns 0. So from that how much is left of 8? obviously 8 is the remainder as 9 took nothing away from 8. Does that make sense and is that the reason?

Hi @illegalhelios,

This gives a good explanation: What is Modulo? (computerhope.com)

1 Like

That’s pretty much it. You’d probably refer to this as 8 cannot go into 9 a whole number of times. Like if you need 9 tickets at the fair to win a cuddly monkey and you have 8 you can get 0 cuddly monkeys, but you do still have 8 tickets remaining. If you had 32 tickets then you could get 3 cuddly monkeys and have 5 tickets remaining.

If you’re using Python3 you’ve already mentioned the relevant two operators the % modulo to get the remainder and // for floor division. There isn’t an operator for it but there is a function that gives both, divmod where the result is quotient then remainder-

print(divmod(8, 11)) print(divmod(8, 7)) print(divmod(8, 8))
3 Likes

That’s useful to know. Thank you for that.

1 Like