Python continue Statements
Like break statements, continue statements are used inside loops. When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop and reevaluates the loop’s condition. (This is also what happens when the execution reaches the end of the loop.)
Let’s use continue to write a program that asks for a name and password. Enter the following code into a new file editor window and save the program as swordfish.py.
while True: print('Who are you?') name = input() if name != 'Joe': continue print('Hello, Joe. What is the password? (It is a fish.)') password = input() if password == 'swordfish': break print('Access granted.')
If the user enters any name besides Joe u, the continue statement causes the program execution to jump back to the start of the loop. When it reevaluates the condition, the execution will always enter the loop, since the condition is simply the value True. Once they make it past that if statement, the user is asked for a password. If the password entered is swordfish, then the break statement is run, and the execution jumps out of the while loop to print Access granted. Otherwise, the execution continues to the end of the while loop, where it then jumps back to the start of the
loop. See Figure for this program’s flowchart.
Run this program and give it some input. Until you claim to be Joe, it shouldn’t ask for a password, and once you enter the correct password, it should exit.
Who are you? I'm fine, thanks. Who are you? Who are you? Joe Hello, Joe. What is the password? (It is a fish.) Mary Who are you? Joe Hello, Joe. What is the password? (It is a fish.) swordfish Access granted.