I am just beginning to dabble in Python, and have started to go through the chapters on learnpython.org. In the \'Loops\' chapter, I have solved the challenge with the follo
3 if's and done :)
if x % 2 == 0:
print x
if x == 237:
break
if x % 2 != 0:
continue
Output
402
984
360
408
980
544
390
984
592
236
942
386
462
418
344
236
566
978
328
162
758
918
Im just going throug this exercise in my "learning the basis thing" and i came out with a similar but somehow worse solution, patrik :(
x = 0
for loop in numbers:
if (numbers[x]) % 2 ==0:
print (numbers[x])
x = x+1
if (numbers[x]) ==237:
break
else:
x =x+1
continue
That's what else
and elif
are for:
for x in numbers:
if x == 237:
break
elif x % 2 == 0:
print x
This is also possible:
try:
i = numbers.index(237)
except:
i = len(numbers)
for n in numbers[:i]:
if not n%2:
print n
you can do that using list comprehension
The solution would be like this:
numbers = [x for ind,x in enumerate(numbers) if x % 2== 0 and numbers[ind+1]!=237 ]
Another method is using itertools
which always comes in useful some way or another:
>>> from itertools import takewhile, ifilter
>>> not_237 = takewhile(lambda L: L != 237, numbers)
>>> is_even = ifilter(lambda L: L % 2 == 0, not_237)
>>> list(is_even)
[402, 984, 360, 408, 980, 544, 390, 984, 592, 236, 942, 386, 462, 418, 344, 236, 566, 978, 328, 162, 758, 918]
So we create a lazy iterator that stops at 237, then take from that even numbers