How do I get a python program to do nothing?

Python

Python Problem Overview


How do I get a Python program to do nothing with if statement?

 if (num2 == num5):
     #No changes are made

Python Solutions


Solution 1 - Python

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()

Solution 2 - Python

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

Solution 3 - Python

you can use pass inside if statement.

Solution 4 - Python

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

Solution 5 - Python

You can use continue

if condition:
    continue
else:
    #do something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPolli EsterView Question on Stackoverflow
Solution 1 - PythonrlmsView Answer on Stackoverflow
Solution 2 - PythonLixView Answer on Stackoverflow
Solution 3 - Pythonsiddharth jambukiyaView Answer on Stackoverflow
Solution 4 - PythonwetbadgerView Answer on Stackoverflow
Solution 5 - PythonImayaView Answer on Stackoverflow