SyntaxError: 'continue' not properly in loop in Python

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Photo from Unsplash

SyntaxError: 'continue' not properly in loop in Python #

The Python "SyntaxError: 'continue' not properly in loop" occurs when we use the continue statement outside of a loop. To solve the error, use the continue statement in a for or a while loop and make sure your code is indented correctly.

syntaxerror continue not properly in loop

Here is an example of how the error occurs.

main.py
if len('hi') == 2: # ⛔️ SyntaxError: 'continue' not properly in loop continue

The continue statement can be used to continue to the next iteration of a for or a while loop.

main.py
for i in range(10): if i % 2 == 0: continue print(i) # 👉️ 1, 3, 5, 7, 9

The example above checks if each number in the range is divisible by 2 and if it is, we continue to the next iteration.

Here is an example that uses a continue statement in a while loop.

main.py
num = 0 while True: num += 1 if num > 10: break if num % 2 == 0: continue print(num) # 👉️ 1, 3, 5, 7, 9

The while loop iterates until its condition returns false or the break statement is used.

The break statement breaks out of the innermost enclosing for or while loop.

Whereas, the continue statement continues to the next iteration of the loop.

Make sure you have indented your code in the loop correctly.

If the code that uses the continue statement is not indented consistently, the interpreter won't recognize it as part of the loop.

If you need to handle a block of code that's not yet implemented, use the pass statement.

main.py
if len('hi') == 2: pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

If you meant to return a value from a function, use the return statement.

main.py
def get_name(): return 'Alice' name = get_name() print(name) # 👉️ 'Alice'

The return statement can be used to return a value and exit the function.

If you don't need to return a specific value and just need to exit the function, simply return.

Conclusion #

The Python "SyntaxError: 'continue' not properly in loop" occurs when we use the continue statement outside of a loop. To solve the error, use the continue statement in a for or a while loop and make sure your code is indented correctly.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.