python - 我可以在 if 语句中不使用 break 来执行此操作吗?

标签 python python-3.x

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

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

最佳答案

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

相关文章:

python : TypeError: 'float' object is not iterable

python - __init__() 需要 1 个位置参数,但 2 个给出了类型错误

python - 尽管 python selenium 中的文档可用,但元素不可见

python - 为什么run_in_executor放在BaseEventLoop中?

python - 如何使用 Google App Engine 管理第三方 Python 库? (虚拟环境? pip ?)

python - |= 在 python 中的用例

python - 如何使用 SQLAlchemy 在 Postgres 中执行 date_trunc 查询

python - 使用 python +/- matplotlib 绘制机器人路径和方向

python - 副窗无槽

python - 从数字串中找出最高和最低的数字