rpiboy
Posts: 110
Joined: Mon Mar 20, 2017 8:39 pm

Need help understanding this code

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?

Idahowalker
Posts: 445
Joined: Wed Jan 03, 2018 5:43 pm

Re: Need help understanding this code

Sun Feb 17, 2019 12:24 am

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
Without knowing why you are deleting my postings, I will not know how...

hippy
Posts: 5969
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Need help understanding this code

Sun Feb 17, 2019 12:43 am

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.

Return to “Python”