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
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
- Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32
- Microsoft Windows 10 Enterprise Version 22H2 OS Build 19045.3693 Experience: Windows Feature Experience Pack 1000.19053.1000.0