0

Trying to find the even numbers in the list but finding the first two...

https://code.sololearn.com/cy8XIjF5kqa7/?ref=app

5th Aug 2017, 1:00 PM
kalooh Kennedy
kalooh Kennedy - avatar
5 Answers
+ 5
# you must separate you loop condition from your display condition: nums = [18,12,25,42,57,61,72,89,91,100] # x=0 # not necessary with 'for' loop b=len(nums)-1 for x in range(len(nums)): if nums [x]%2==0: num=nums [x] print (nums [x]) # x=x+1 # not necessary with 'for' loop # using while loop: nums = [18,12,25,42,57,61,72,89,91,100] x=0 b=len(nums)-1 while x < len(nums): if nums [x]%2==0: num=nums [x] print (nums [x]) x=x+1
5th Aug 2017, 1:06 PM
visph
visph - avatar
+ 7
nums = [18,12,25,42,57,61,72,89,91,100] x=0 while x < len(nums): if nums[x]%2 == 0: print(nums[x]) x=x+1 # Of course a for loop would be more natural here :)
5th Aug 2017, 1:15 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 6
You constructed a while loop with a condition of x%2==0. As soon as it becomes False, it stops completely and ends the program's execution. Try adding another condition - check if the iterator is lower than len(nums) and check for the even/odd status inside the loop only.
5th Aug 2017, 1:04 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 5
Anyway, why do you affect the nums[x] value to num? num=nums [x] print (nums [x]) ... should be: num=nums [x] print (num) ... or (more logical, as you don't seems to use num elsewhere): # num=nums [x] # not necessary print (nums [x])
5th Aug 2017, 1:10 PM
visph
visph - avatar
+ 2
thanks guys finally got it nums = [18,12,25,42,57,61,72,89,91,100] x=0 b=len(nums)-1 while x<=b: if nums [x]%2==0: num=nums [x] print (nums [x]) x=x+1
5th Aug 2017, 1:49 PM
kalooh Kennedy
kalooh Kennedy - avatar