Sifting even number with for and append functions


Sifting even number with for and append functions


def sieve(numbers):
odd =
for i in numbers:
if (i//2) != 2:
odd.append(i)
return odd

a = [2, 4, 6, 8, 5]
print(sieve(a))

Output:
[2, 6, 8]



I want this function to sift even numbers out and as you can see my if statement is using floor division to divide the value of i to 2 and if it is not equivalent to 2 then it is an odd number. However, the output I get only retains the even numbers. Why is that?





Because dividing a number by 2 isn't how you check if it's odd... Your code checks if the number is equal to 4 (or 5).
– Aran-Fey
Jun 29 at 10:49





Possible duplicate of How to determine if an integer is even or odd
– Aran-Fey
Jun 29 at 10:50





Try it with modulo: if i%2 != 0:
– Igle
Jun 29 at 10:54


if i%2 != 0:




1 Answer
1



I think you have a confusion with // operator. The // is a floor division operator which is very similar to the division operator /. It returns the result of division without floating numbers. You can check here:


//


//


/


>>> a = [2, 4, 6, 8, 5]
>>> for i in a:
print i//2



Output:


1
2
3
4
2



In order to find odd/even numbers you can use modulo operator % as @lgle said:


%


>>> for i in a:
print i%2



Output:


0
0
0
0
1






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV