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

100 Views Asked by At

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.

3

There are 3 best solutions below

0
Ken Williams On BEST ANSWER

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.

0
NightRider On

I think u should change code into this

i=0
while i < len(w):
    if w[i].isdigit():
        return True
    i+=1
return False

because your function only check first character is digit or not

1
Chetan Singh On

You are right to be concerned. Your while loop would in fact become an infinite loop if there was no "break" statement included, which would prevent the function from functioning as intended. Depending on whether or not the first character is a digit, the loop will either return True or False at the beginning. The function will have returned a value by now, therefore the "i+=1" statement will never be reached.

def check_digit_placement(w):
    if w.isalpha():
        return True
    else:
        i = 0
        while i < len(w):
            if w[i].isdigit():
                return True
            else:
                i += 1
        return False