jeudi 5 janvier 2017

Python while if not working

I'm given with an array with numbers. I'm trying to build a program that identifies if the number is an even or odd number. Here's what I've done.

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
i=0
while i <= len(a):
    if a[i] % 2 == 0:
        print(a[i], " is an even number")
        i = i + 1
    else:
        print(a[i], " is an odd number")

I was thinking since a[0], a[1] represents 1, 4, I thought that I can use a[i] where i increases until the length of a. But this code gives me an infinite loop.

This is the only way I figured to use individual numbers in array. I tried using

if a%2==0:
    print(a, " is an even number")

But that gave me an error.

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire