Page 1 of 1

Need help understanding this code

Posted: Sat Feb 16, 2019 11:27 pm
by rpiboy

Code: Select all

class EvenOnly(list):
    def append(self, integer):
        if not isinstance(integer, int):
            raise TypeError("Only integers can be added")
        if integer % 2:
            raise ValueError("Only even numbers can be added")
        super().append(integer)
        
e = EvenOnly()
e.append(2)
I'm trying to understand this code and what I don't understand is " if integer % 2:
raise ValueError("Only even numbers can be added")"

If 2 % 2 which 2 is an even number shouldn't it raise an error since it is true?

Re: Need help understanding this code

Posted: Sun Feb 17, 2019 12:24 am
by Idahowalker
rpiboy wrote:
Sat Feb 16, 2019 11:27 pm

Code: Select all

class EvenOnly(list):
    def append(self, integer):
        if not isinstance(integer, int):
            raise TypeError("Only integers can be added")
        if integer % 2:
            raise ValueError("Only even numbers can be added")
        super().append(integer)
        
e = EvenOnly()
e.append(2)
I'm trying to understand this code and what I don't understand is " if integer % 2:
raise ValueError("Only even numbers can be added")"

If 2 % 2 which 2 is an even number shouldn't it raise an error since it is true?
Even number as integer modulo 2 = 0.

Odd number as integer modulo 2 = 1

0 = false
1 = true = raise an error

Re: Need help understanding this code

Posted: Sun Feb 17, 2019 12:43 am
by hippy
rpiboy wrote:
Sat Feb 16, 2019 11:27 pm
If 2 % 2 which 2 is an even number shouldn't it raise an error since it is true?
I would have written it as ...

if ( integer % 2 ) != 0:

or more likely ...

if ( integer & 1 ) != 0:

They are all the same, but these two help avoid the sort of confusion it has caused you.