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 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
April 10, 2013 at 11:06 pm