gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:01:58 26 4
gpt4 key购买 nike

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

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

最佳答案

您可以改用 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

关于python - 我可以不在 if 语句中使用 break 来做到这一点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55426875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com