Lecture 41: The break-else syntax structure in Python loop statements

1. The idea of ​​​​executing actions after the loop ends normally

When executing a while loop statement or a for loop statement, if the loop ends normally, and the break statement in the loop body is not executed to cause the loop to exit, some requirements may want to perform certain operations after the loop ends normally.

If you want to perform certain actions after the loop ends normally, there are two implementations:

  • Do something after the loop ends normally by controlling a boolean variable

    • Define a Boolean variable before the loop, the variable stores the Boolean value False, and define a conditional judgment in the loop body. When this condition is met, set the value of the Boolean variable to True, and then execute break to jump out of the loop. After the loop ends, use if to judge whether the value of the Boolean variable is False, if it is False, it means that our loop exits normally, and exits without a break, and some operations are performed at this time.
  • Do something with an else clause

    • In Python, a break-else structure is also provided for the loop statement. You can add an else clause after the while and for-in statements. When the loop ends normally,

Guess you like

Origin blog.csdn.net/weixin_44953658/article/details/130573080