while 循环末尾缺少“break”什么时候会导致无限循环?

问题描述 投票:0回答:1

我创建了一个愚蠢的函数来查看字符串是否包含数字。

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

该函数有效,但我仍然有点担心,如上面的评论所示:如果没有适当的中断,循环会卡在某个 i 处,无限多次返回“True”或“False”吗?如果可以的话,为什么这个功能看起来有效呢?任何帮助将不胜感激。

python while-loop break
1个回答
0
投票

我认为你应该将代码更改为这样

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

因为你的函数只检查第一个字符是否是数字

© www.soinside.com 2019 - 2024. All rights reserved.