Hi! Can somebody explain why i need the "if x%2 == 1" part? Please, i'm just learning python datastructure

https://onlinegdb.com/WF0MOPqNq

+7 votes

https://onlinegdb.com/WF0MOPqNq

0 votes

first you need to know that % = remainder of division

the division is x / 2

the 1 means it's not integer because it's left

if you put an even number it will come out like

10 % 2 = 5 == integer

I think that's it, sorry if I did a mistake thx.

(if x/2 the remainder of the division = 1 it was a odd number)

+1 vote

#example: that will check if what you writed it's a ood number or a even number.

printar = int(input(""))

if printar%2 == 1:

print('its a ood number')

elif printar%2 == 0:

print('its a even number')

printar = int(input(""))

if printar%2 == 1:

print('its a ood number')

elif printar%2 == 0:

print('its a even number')

0 votes

x is a variable , % implies mod operation that gives remainder obtained on division, so x%2 is used to check if it gives remainder 1 implying odd number or otherwise is an even number. Now the x in range 10 will generate numbers from 1 to 10 one at a time and check this condition. Without checking this condition you will get a list of all numbers from 1 to 10 whereas now you only get odd numbers ,since values of x not following the condition are not included.

0 votes

Your code is

odds = [x for x in range(10) if x % 2 == 1]

and as the name correctly suggests, odds hold all the odd numbers from 1 to 10, i.e.: 1, 3, 5, 7, 9.

The line says, 'add all the x to the list if they are odd'. Odd is decided by checking the modulus 2 of x to be 1.

Check out the Python Operators.

% is the modulus, it tells you the remainder of a division. E.g.: 100 % 12 = 4, because 100 - 8 * 12 = 100 - 96 = 4.

x % y returns values in the range [0, y), i.e., 0 included, but y not included.

I hope this helps.

commented
Oct 10, 2022
by
Pensa Ativo
(260 points)

I think he's not gonna understand what you said

Yes.

I wouldn't say it adds x to a list as there the list is constructed with elements already in it, rather than adding them one by one.

Perhaps a better phrase would be that `odds` is a list that consists of any x, where

a) x is in range(10) --> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

AND

b) x is an odd number (i.e.: x % 2 == 1)

I wouldn't say it adds x to a list as there the list is constructed with elements already in it, rather than adding them one by one.

Perhaps a better phrase would be that `odds` is a list that consists of any x, where

a) x is in range(10) --> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

AND

b) x is an odd number (i.e.: x % 2 == 1)

...