How do I get a Python
program to do nothing with if statement?
if (num2 == num5):
#No changes are made
@TomSawyer to stop a Python program early, do import sys first and then sys. exit() if you want to exit but report success or sys. exit("some error message to print to stderr") .
Empty Statement: A statement which does nothing is called empty statement in Python. Empty statement is pass statement. Whenever Python encounters a pass statement, Python does nothing and moves to the next statement in the flow of control.
Python pass Statement The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
You could use a pass
statement:
if condition:
pass
Python 2.x documentation
Python 3.x documentation
However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if
statement.
If you have something like this:
if condition: # condition in your case being `num2 == num5`
pass
else:
do_something()
You can in general change it to this:
if not condition:
do_something()
But in this specific case you could (and should) do this:
if num2 != num5: # != is the not-equal-to operator
do_something()
The pass
command is what you are looking for. Use pass
for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.
For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:
if num2 != num5:
make_some_changes()
This will be the same as this:
if num2 == num5:
pass
else:
make_some_changes()
That way you won't even have to use pass
and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.
You can read more about the pass
statement in the documentation:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
if condition:
pass
try:
make_some_changes()
except Exception:
pass # do nothing
class Foo():
pass # an empty class definition
def bar():
pass # an empty function definition
you can use pass inside if statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With