-1

This is suposed to check if a number is even or odd by dividing it by 2 but it is always looking at the same number

 a= [1,2,5,7,8];
    i=0
    c=a[i]/2.0;
    d=0;
    b=len(a);
    while i < b:
            if (c).is_integer():
                        i=i+1;
                        d=d +1;         
            else:
                        i=i +1;
    print(d);

The answer given to me is 0 but if the first number on the list even the answer given is 5.

Apparently it is always detecting the number a not integer, so is there any way to check if the number has or not decimals?

dave
  • 4,654
  • 3
  • 23
  • 38
Daniw
  • 9
  • 3

2 Answers2

1

You are not moving through each instance of c, so currently you are just looking at the first element over and over.

a= [1,2,5,7,8]
i=0
d=0
b=len(a);
while i < b:
    c=a[i]/2.0
        if (c).is_integer():
                i=i+1
                d=d +1         
        else:
                i=i +1
print(d)

You also do not need the ; after each line that is more of a java thing. You could also look into for loops.

a = [1, 2, 5, 7, 8]
for i in a:
    if (c).is_integer():
            i=i+1
            d=d +1
print(d)

This uses less variables and is a better format. You should look up a style guide for python that might help you a lot. Here is a link to one python style guide.

Justin Minsk
  • 46
  • 1
  • 5
0

I guess you want to iterate the list a, then you need to put c=a[i]/2.0; into while loop

a = [1, 2, 5, 7, 8]
i = 0
d = 0
b = len(a)
while i < b:
    c = a[i] % 2
    if (c == 0):
        i = i + 1
        d = d + 1
    else:
        i = i + 1
print(d)
wlhe
  • 61
  • 3