La Boina Roja

Linux, the struggles are real!

Get even with Modulo!

1 Comment

DOKONUS 2c657

If you just started learning Python, one off the things people like to trick you with, is asking you to create a function with a code that should do something if it’s outcome is even. They expect you’ll mess around with stuff like “int”, type() etc.

But don’t be afraid  photo smile.gif it is very easy to create such a piece of code. Let’s say the parameter of your function is x and the code should evaluate (=check) if x is even. This is how you do it:

x % 2 == 0

See the % is called the Modulo, and when used as an arithmetic operator it returns the remainder of an integer division.

9 % 2 will return the remainder 1, 2 goes into 9 evenly 4 times.

12 % 4 there is no remainder, 4 goes into 12 evenly 3 times.

And as you know, no remainder equals to 0.

And of course if the outcome should be uneven you would use this:

x % 2 != 0

One thought on “Get even with Modulo!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s