Exit if Statement in Python

Using break Statement

Use the break statement to exit if statement in Python.

The break statement is used to terminate the loop prematurely. This statement is commonly utilized in loops to exit from them if a particular condition was met.

In the above example, we used a for loop to iterate over a sequence of numbers that were created using a range() function. Here, the range() created a sequence from 0 to 5.

In each iteration, we used the print() function to print the current number (num) followed by an if statement to determine if the num is equal to 3.

If it was, the loop was terminated due to a break statement. Outside the loop, we used another print statement to display a message on the console saying the loop was terminated.

What about the user input? Can we still exit the if statement in Python if we are supposed to exit the loop based on the user’s input? See the following example.

This example resembles the previous one; however, we used the input() function to prompt the user and take input from him. Then, the if statement was used with an or operator to check multiple conditions; in our case, we checked if the user’s input was equal to y or Y.

The if block would be executed if at least one conditional expression was fulfilled; otherwise, the loop would continue with its next iteration.

Using return Statement

Use the return statement to exit if statement in Python.

The primary use of the return statement is to return one or multiple values from a function; however, we can also use it to exit from a loop if a certain condition is satisfied.

In the above example, we used the def keyword to define the evenOdd() function. Inside this function, we wrote logic to check if number is even or odd.

Outside this function, we invoked it as evenOdd() which returned "2 num is even" as it checked if statement and returned True as num is even.

Similarly, we can exit based on the user’s input; see the following example:

Using sys Module

Use the exit() function of the sys module to exit if statement in Python.

Let’s take another example below:

The code snippets resembled the examples learned using the break statement; however, we used the sys.exit() function here to exit if statement in Python. The sys.exit() was used to exit the interpreter that’s why no statement was executed after the sys.exit() function.

The sys.exit() not only exits the if statement but exits the Python script as well. This is the reason, the sys.exit() is not recommended because we have comparatively better ways to get the same results; for example, break and return statements.

Remember, the sys.exit() function exits the script with a SystemExit exception.

That’s all about how to exit if statement in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *