Python: break(), continue(), exit() and quit()

141 阅读1分钟

1.break() - The break keyword is also used inside a loop to exit the loop early. When the break statement is executed, the loop will immediately terminate and control will resume after the loop. Here's an example:

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

This will print the numbers 0 through 4, and then exit the loop when i equals 5.

2.continue: The continue keyword is used inside a loop (for loop or while loop) to skip the current iteration and move on to the next iteration of the loop. In other words, when the continue statement is executed, the loop will immediately jump to the next iteration without executing the code below the continue statement. Here's an example:

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

This will print all the odd numbers between 0 and 9, because the print statement is skipped whenever i is even.

3.exit() - The exit function is used to exit the Python interpreter. When the exit function is called, the interpreter will immediately terminate. Here's an example:

print("Hello, world!")
exit()
print("This line will never be executed.")

In this example, the exit function is called after the "Hello, world!" message is printed. As a result, the interpreter will immediately terminate and the last print statement will never be executed.

4.quit() - The quit function is similar to the exit function, in that it is used to exit the Python interpreter. However, quit is actually an alias for exit in Python. Here's an example:

print("Hello, world!")
quit()
print("This line will never be executed.")

In this example, the quit function is called after the "Hello, world!" message is printed. As a result, the interpreter will immediately terminate and the last print statement will never be executed, just like with the exit function.