Each Answer to this Q is separated by one/two green lines.
How do I get a
Python program to do nothing with if statement?
if (num2 == num5): #No changes are made
You could use a
if condition: pass
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 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()
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 (num2 == num5): for i in : #do nothing do = None else: do = True
or my personal favorite
if (num2 == num5): while False: #do nothing do = None else: do = True
You can use continue
if condition: continue else: #do something