Unix
Unix

Reputation: 89

Converting a nested for loop to a nested while loop

my_data = [4, 8, 15, 16, 23, 42]
index = 0
for item in my_data:
    k = 0
    for i in range(2, item+1):
        if (i % 2 == 0):
            k += 1
    my_data[index] = k
    index += 1
print(my_data)

The above code takes all the elements of the given list and divides them by 2, and it works all fine, however I was trying to convert it into while loop for sake of practice,but for some reason I am getting no error, but the code keeps running and I had to force stop it.

i = 0
while i < len(my_data):
    j = 2
    while j < i+1:
        if j % 2 == 0:
            j += 1
    my_data[i] = j
    i += 1
print my_data

And here is the method I have tried to implement which seems to not work as far as I am concerned. If someone could clarify it for me I would appreciate it. Thank you in advance.

Upvotes: 0

Views: 84

Answers (3)

Shakeel
Shakeel

Reputation: 2015

If you are just trying to divide each item of a list using while you also try this way.

my_data = [4, 8, 15, 16, 23, 42]
index = 0
while len(my_data) > index:
    my_data[index] = int(my_data[index]/2)
    index +=1

print(my_data)

Upvotes: 1

Moussa
Moussa

Reputation: 510

your second while loop moves forward only if j is pair and if j is not (since j increase only by 1) the while loop will loop for ever. you've made a little mistake by replacing k with j, and you should continue using k

i = 0
while i < len(my_data):
    j = 2
    k = 0
    while j < i+1:
        if j % 2 == 0:
            k+=1
        j += 1
    my_data[i] = k
    i += 1
print my_data

Upvotes: 1

enamoria
enamoria

Reputation: 916

At line 5:

if j % 2 == 0:

When i==3 and j==3, the if statement is ignored. j can't be increased. It will be looped forever, since the stop criterion is j<i+1
Just add an else statement to handle that case

Upvotes: 1

Related Questions