如果不在if语句中使用break,我可以这样做吗?

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

我已经远远超过了我的编码课程,所以我比开始学期时所需的知识多一点。编辑请原谅define函数的缩进错误。

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

python python-3.x
1个回答
3
投票

您可以使用while循环,其条件与if语句中的条件相反。如果循环完成而没有破坏,则指数position将等于上限needle_characters,因此使用position == needle_characters作为原始else循环的for子句的等效条件。

更改:

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
© www.soinside.com 2019 - 2024. All rights reserved.