I am learning Python, and struggling with conditions of a for loop. I must be missing something simple. I have a list with some int values, and I want to (1) print all even numbers and (2) only print values up to a certain index. I can print the even numbers fine, but cannot seem to print only to a certain index.
numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345]
Prints all numbers in list -- ok:
for i in numbers: print iPrints all even numbers in the list -- ok:
for i in numbers: if i % 2 == 0: print i
Let's say I want to only print even numbers up to and including the entry with the value 980 -- so that would be 402, 984, 360, 408, 980.
I have tried, unsuccessfully, to implement a count and while loop and also a conditional where I print numbers[n] < numbers.index(980).
.index(...)is almost irrelevant imho; that is not to say that is not useful, but I have almost never needed to use it. What it does is it finds the first occurrence of a number, that is,index(980)would find the index of the first time the number980appeared in the list.for x in numbers: if x%2==0: print x.