Python - Doing nothing with an if statement

When you don’t want to do anything in an if statement when a condition is met or not met, you can use the pass statement.

If statement that does nothing

if <condition>:
    pass
else:
    pass

Explanation

The pass statement does nothing. It is used when you want to explicitly indicate that nothing should be done, or when Python’s syntax does not allow for an empty block.

For example, you must always write some code inside the blocks of if and else statements. However, you can use pass to avoid a syntax error when you don’t want to do anything.

The following code will cause an IndentationError because there is no statement inside the if block:

if value >= 0:
else:              # IndentationError: expected an indented block after 'if' statement
    value = 0
You can solve this by using pass:
if value >= 0:
    pass
else:
    value = 0

Sample Code

The following code does nothing when the variable value is 0 or more, and prints ‘The value is negative.’ when value is less than 0.
if value >= 0:
    pass
else:
    print('The value is negative.')

References

Test Environment