Home > Mobile >  While loop keeps going back to end condition
While loop keeps going back to end condition

Time:11-09

I'm just going over some python basics, and wrote some code that I thought would print every even element inside of a list:

def print_evens(numbers):
    """Prints all even numbers in the list
    """
    length = len(numbers)
    i = 0
    while i < length:
        if numbers[i] % 2 == 0:
            print (numbers[i])
            i  = 1
            
print_evens([1, 2, 3, 4, 5, 6])

I'm not sure why but the loop doesn't go past the end condition and just keeps cycling back and forth. I feel I'm missing something very simple.

If I had to guess where the problem lies, I'd say it's with the if statement, though I'm not sure what would be wrong about it.

CodePudding user response:

The problem is that when you start with 1 the variable i never get updated, because it's not even. So the solution is to increment the i every time without a condition:

while i < length:
        if numbers[i] % 2 == 0:
            print (numbers[i])
        i  = 1

CodePudding user response:

If you don't want to bother with indexes you can loop directly on the list items.

def print_evens(numbers):
    """Prints all even numbers in the list
    """
    for n in numbers:
        if n % 2 == 0:
            print(n)
  • Related