Exit the if Statement in Python

  1. Exit an if Statement With break in Python
  2. Exit an if Statement With the Function Method in Python

This tutorial will discuss the methods you can use to exit an if statement in Python.

Exit an if Statement With break in Python

The break is a jump statement that can break out of a loop if a specific condition is satisfied. We can use the break statement inside an if statement in a loop.

The main purpose of the break statement is to move the control flow of our program outside the current loop. The program below demonstrates how you can use the break statement inside an if statement.

for i in range(10):
    print(i)
    if i == 5:
        break

Output:

0
1
2
3
4
5

We developed a program using the break statement that exits the loop if the value of the variable i becomes equal to 5. The only thing missing with this approach is that we can only use it inside an if statement enclosed inside a loop. We cannot use this inside a nested-if statement, as shown below.

i =0
if i%2 == 0:
    if i == 0:
        break
    if i > 0:
        print("even")
print("Broken")

Output:

File "<ipython-input-3-efbf2e548ef1>", line 4
    break
    ^
SyntaxError: 'break' outside loop

If we want to exit out of a pure if statement that is not enclosed inside a loop, we have to utilize the next approach.

Exit an if Statement With the Function Method in Python

We can use an alternative method to exit out of an if or a nested if statement. We enclose our nested if statement inside a function and use the return statement wherever we want to exit.

The following code modifies the previous example according to the function method.

def something(i):
    if i%2 == 0:
        if i == 0:
            return
        if i > 0:
            print("even")

if __name__ == "__main__":
    something(0)
    print("Broken out")

Output:

Broken out

We developed a program that uses the function method to exit out of multiple if statements with the return statement. This method is clean and far superior to any other methods that can be used for this purpose.

A lot of forums mention another method for this purpose involving a goto statement. By default, we know that Python has no support for a goto statement.

But, in 2004, a goto module was released as part of an elaborate April fools day joke that users began to use seriously. We didn’t mention it because it is not a graceful method and its official page notes that it should never be used inside any production code.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Condition

  • Use the if not Condition in Python