0
Trying to find the even numbers in the list but finding the first two...
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
+ 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 :)
+ 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.
+ 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])
+ 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