Why is this loop infinite?

Asked

Viewed 103 times

2

I wanted to stop the loop when t is at 5. So I counted -1, but it does not go back to while to check the condition and turns a loop infinite.

text = 'abcdefghij'
t = 10

while t != 5:
    for i in text:
        print(i)
        t -= 1
        print(t)
´´´´

2 answers

7

This code does not make much sense and is very inefficient, but if you really want to do what is described in the question it would be like this:

text = 'abcdefghij'
t = 10
for i in text:
    print(i)
    t -= 1
    print(t)
    if t == 5:
        break

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You don’t have an algorithm that requires a loop inside the other, you probably used one while when all I wanted was one if.

It is not the most common but as it needs to stop something in the middle the most correct in this case perhaps is to do only the while:

text = 'abcdefghij'
t = 10
while t != 5:
    print(text[10 - t])
    t -= 1
    print(t)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

6


The variable t is not being used in the right way. From the moment you enter the second loop it will always scroll through the letters of text decreasing by 1 in t

while t != 5:
    for i in text:
       print(i)
       t -= 1
       print(t)

At the end of the first interaction on according to loop, the for i in text:, the value of t is 0. It exits the loop and 0 is still different from 5. It re-enters the for loop and when it exits the value is -9 and so on.

The value of t will always be different from 5

Browser other questions tagged

You are not signed in. Login or sign up in order to post.