如何检查for循环何时完成python3

2024-05-20 00:38:50 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

i = 'string'
for x in i:
    print('hi this should print multiple times')
    #somthing that detects when for loop is finished
#or something that detects that here

这很简单,我发现的所有例子要么不起作用,要么非常复杂,我只是在寻找一些简单的方法,因为我确信有一个很好的方法来做到这一点,但我没有找到它

我找到了一些链接,但这些链接对我来说并不实用:

this pagethis page


Tags: 方法inforstringthat链接pagehi
1条回答
网友
1楼 · 发布于 2024-05-20 00:38:50

你想达到什么目标?如果您只是想在for循环完成后运行一些代码,那么您可以将这段代码放在for循环之后

如果要检查循环是否“正常”完成(不遇到break语句),可以使用for/else语句:

    for x in range(2, n):
        if n % x == 0:
            print( n, 'equals', x, '*', n/x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

资料来源:https://book.pythontips.com/en/latest/for_-_else.html

相关问题 更多 >