'Using exec 'continue' in loop

Can anyone explain why using pass works in this code but continue throws an error: SyntaxError: 'continue' not properly in loop?

f = 'pass'  # Works
f = 'continue'  # Fails

for i in range(10):
    if i < 5:
        exec f
    print i

Just to provide some context, I was checking if a keyword could be stored in a variable:

def magic_print_i(f):
    for i in range(10):
        if i < 5:
            exec f
        if i % 3:
            continue
        print i

magic_print_i("continue")


Solution 1:[1]

Because exec doesn't carry the context over to the statement being executed.

pass can be used anywhere, so the context doesn't matter. continue can only be used in the context of a loop, but that context is not available to exec.

You can only use continue in an exec statement if the loop itself is also part of the executed code:

f = 'for i in range(10): continue'
exec f

In other words, you can only use exec for complete statements, where a single continue (or break) is not complete.

Solution 2:[2]

To apply exec on a dynamically selected keyword within a loop context, use string formatting:

selected_keyword = 'break'

exec(
f'''
for i in range(5):
    #do stuff
    {selected_keyword}
''')

Solution 3:[3]

a continue isn't complete. It's like the other half of a break. Whereas exec executes complete commands, as like in pass

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martijn Pieters
Solution 2 AturSams
Solution 3 Slass33