Search code examples
python-3.xlistfor-loopwhile-loopslice

Function repeating forever


keeps on running through the loop even though the while loop condition should turn it off?

userinput = str(input(''))  

def input_read() :
    newstring1 = []
    EB_to_01 = []
    placeholder = 0
    y = 0

    while y <= len(userinput) :
        for i in userinput[y:] :
            if i != 'E' and i != 'B' :
                newstring1.append(i)
                y += 1
            else : break

        placeholder += 1

        for i in userinput[y:]:
            if i == 'E' :
                newstring1.append(placeholder)
                EB_to_01.append(i)
                y += 1
            elif i == 'B' :
                newstring1.append(placeholder)
                EB_to_01.append(i)
                y += 1
            else: break
    
    print(newstring1 ,'\n',EB_to_01)
    return EB_to_01


input_read()

I tried removing the slicing on the for loops and it doesn't endlessly repeat. I need the slicing though because in short I'mm trying to add all E's and B's into a separate list and replace all E's and B's in the input with numbers in the order they are in the string.


Solution

  • The condition of the while loop should be < and not <= because the loop starts at y = 0 and ends at one less than the length so never reaches the stop condition.

    One handy tool when you have endless loops is putting in print statements at key points (like indexes) to see what's happening.