Ask Your Question
2

How to stop the for-loop when a specific condition is fulfilled?

asked 2022-11-18 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-28 04:00:00 +0000

devzero gravatar image

You can stop a for-loop when a specific condition is fulfilled by using the break statement. The break statement exits the loop immediately when it is executed.

Here's an example:

for i in range(10):
    if i == 5:
        break
    print(i)

In this example, the for-loop will run from 0 to 9. However, when i is equal to 5, the break statement is executed and the loop is exited immediately. The program will output:

0
1
2
3
4

Note that if the condition is not met, the loop will continue until it reaches the end of its iteration.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-11-18 11:00:00 +0000

Seen: 13 times

Last updated: May 28 '21