Search code examples
pythonwhile-loopbreak

When would the absence of "break" at the end of a while loop lead to infinite loops?


I created a silly function to see if a string contains digits or not.

def check_digit_placement(w):
    if w.isalpha():
        return True
    else:
        i=0
        while True:
            if w[i].isdigit():
                return True    #Would the absence of "break" here lead to an infinite while loop?
            else:
                return False    #And here too.

            i+=1

          if i>len(w):
              break

The function works, but I am still a bit concerned, as indicated in the comments above: without a proper break, would the loop get stuck at some i, returning "True" or "False" infinitely many times? And if it would, why then does the function seem to work? Any help would be greatly appreciated.


Solution

  • The short answer to your question: if you return from a function, you don't need to also break out of any loops executing in that function. They will terminate fine when the function returns.