我可以在 if 语句中不使用中断来做到这一点吗?



我已经远远领先于我的编码课程,所以我知道的比学期开始时需要的要多一点。编辑请原谅定义函数的缩进错误。

编辑暂时删除。 非常感谢大家的反馈。我会暂时把它放回去。

您可以改用 while 循环,其条件与 if 语句中的中断条件相反。如果循环完成而不中断,则索引position将等于上限needle_characters,因此请使用 position == needle_characters 作为原始 for 循环的 else 子句的等效条件。

改变:

for position in range(needle_characters):
    if haystack[counter+position] != needle[position]:
       break
else:
    return counter

自:

position = 0
while position < needle_characters and haystack[counter+position] == needle[position]:
    position += 1
if position == needle_characters:
    return counter

相关内容

最新更新