Declan Lunney
Declan Lunney

Reputation: 31

output all of the even numbers from a given ist, one per line

The input is

1
2
5
7
8
9
10
end

The output I want is 2 8 10

line=raw_input()
lines = []
i = 0
while line != "end":
   lines.append(int(line))
   line=raw_input()
for i in range(len(line)):
    if line[i] % 2==0:
        print line
    i = i + 1

Terminal keeps saying not all arguments are converted during string formatting.

Upvotes: 1

Views: 105

Answers (3)

Noctis Skytower
Noctis Skytower

Reputation: 22031

Your code could be considerably shorter. The following works but does not handle errors:

import sys
for line in sys.stdin:
    if 'end' in line: break
    if not int(line) & 1: sys.stdout.write(line)

Upvotes: 0

vks
vks

Reputation: 67988

You can use filter here as well.

print filter(lambda i:not i%2,map(int,x.split()))

where x is 1 2 5 7 8 9 10.

Output: [2, 8, 10]

Upvotes: 1

NPE
NPE

Reputation: 500773

1) The

for i in range(len(line)):

should be

for i in range(len(lines)):

2) The

if line[i] % 2==0:

should be

if lines[i] % 2==0:

3) Also, you don't need to increment i since the for loop is already doing this for you.

Finally, a slightly more concise way to write that loop is:

for line in lines:
    if line % 2 == 0:
        print line

Upvotes: 0

Related Questions