ksp ksp - 7 months ago 9
Python Question

Python - Loop is only repeating first output

I don't know what's wrong with my code below. The loop is iterating through all the elements in the list but only repeating first output.

I am trying to print even-indexed and odd-indexed characters as space-separated strings on a single line.

Example:

animals = ['elephant', 'monkey', 'tiger']

My code is printing the below

Out[33]:

eehn lpat

eehn lpat

eehn lpat

The output should be:

eehn lpat

mne oky

tgr ie




Here is my python 2 code:

animals = ['elephant', 'monkey', 'tiger']
w=0
even=""
odd=""


for animal in animals:
while (w<len(animal)):
if (w%2==0):
even=even+animal[w]
if (w%2!=0):
odd=odd+animal[w]
w=w+1
print even+' '+odd


Thanks for your help!

Answer

It's because you only assign w once, at the top. You should assign it inside the for loop each time. Likewise even and odd.