I am trying to understand this code but the "if not x%2:" is quite confusing. It has the same result as "if x==2".
count_even = 0
for x in range(1,9):
if not x % 2:
count_even+=1
I am trying to understand this code but the "if not x%2:" is quite confusing. It has the same result as "if x==2".
count_even = 0
for x in range(1,9):
if not x % 2:
count_even+=1
No, it's not the same, the first statement is a evaluating if x
is odd. Why? In python 0
evaluates to False
and the %
operator is module, that returns the quotient of the two items.
In the second approach you are just saying if x
is equal to 2
x%2
will return 0 when x is even and 1 when x is odd.
So this if
statement evaluates to true
when x is even and false
when x is odd.
if not x%2
Modulo operator calculates the remainder of number x w.r.t number y. And in your example x is ranging from 1-9 and y is given as 2.
So first, x%2
will evaluate to either 1 or 0 based whether x is odd number or even number respectively.
for example:
for x=1 , x%2 = 1%2 (calculating the remainder) = 1
for x=2 , x%2 = 2%2 = 0
Similarly, x=3, 3%2 = 1 (remainder)
And so on...
Now, if it is even number meaning evaluating to 0 which is equivalent to False and then not
operator is negating the result i.e. not(False) == True
,hence condition becoming True
So, when if condition is coming out to be True
then, your code is incrementing the count of even number.
Hope this helps!.
#Hai let me give you one example you can get clarify your doubt !!!
event_squares=[]
for x in range(10):
if x%2: # here conditions True means x is odd(1%2=1(True),3%2=1(True)
event_squares.append(x*x)
print(event_squares)
output=[1, 9, 25, 49, 81, 1, 9, 25, 49, 81]
event_squares=[]
for x in range(10):
if not x%2:# means not True=False;0%2=0(False),2%2=0(False)
event_squares.append(x*x)
print(event_squares)
output=[0, 4, 16, 36, 64]
#list comprehension way
event_squaes=[x*x for x in range(10) if not x%2]
print(event_squares)
output=[0, 4, 16, 36, 64]