Home > Enterprise >  Please point out how I have managed to create an infinite loop
Please point out how I have managed to create an infinite loop

Time:10-20

def split_and_join(line):
    x=line.split()
    n=0
    while n< len(x):
        if n%2==0:
            x.insert(n,"-")
            n =1
        else:
            pass
    print("".join(x))

At what point have I made the error? I know I have managed to create an infinite while loop, but I don't want the complete solution just the point where I forgot a detail or something.

CodePudding user response:

I think you've forgotten to add the n =1 statement after your else block and because of that the value of n never changes and constantly stays 0. Which leads to an infinite loop.

I would also recommend a for loop here instead since you know the exact number of times that the loop should be iterated i.e len(x). It would avoid having to specify the increment.

  • Related