Exit if Statement in Python

The if statement is one of the most useful and fundamental conditional statements in many programming languages. We use the if statement to check whether a condition is True or False and execute some code based on the result. We generally provide an alternative code, which is to be executed when the condition of the if statement fails, using the else statement.

Exit if Statement in Python

This tutorial will demonstrate how to exit if statement in Python.

Using the break statement

The break statement is used to break out of a loop in Python. We cannot directly use this with the if statement. However, we can work around it using a loop.

We can use the while loop and create an infinite loop by providing a True condition. We put the if statement within this loop and use the break statement whenever we want to exit if statement in Python. It will directly break out of the loop and resume program execution.

We implement this in the code below.

Output:

Within if statement
If statement exited!

In the above example, we can observe that the if statement is exited after encountering the break statement.

Using the return statement

We use the return statement whenever we define a function to return some value. The function execution is exited automatically whenever the return statement is encountered in the function definition. If the return statement is missing then the function returns None value by default.

We can put the if statement within the function and use the return statement to exit the function definition which automatically exits the if statement.

See the code below.

Output:

Within if statement
If statement exited!

Using the try and except statements

Python is efficient in exception handling. Exceptions are the errors that are encountered within the code that disrupt program execution. There are different types of exceptions in Python.

The try and except statements are used to work with exceptions in Python. We put code that may raise an exception within the try block. We put an alternative code within the except block. If the code in the try block raises an exception, then the code of except block is executed.

To raise manual exceptions we use the raise statement. We can use a combination of these statements to exit if statement in Python.

We can raise an exception in the if block. Whenever this exception is raised, the program execution goes to the except block. We can put the pass keyword in the except code block which executes nothing when encountered.

The above-mentioned logic is implemented below.

Output:

Within if statement
If statement exited!

Conclusion

To conclude, we discussed several methods to exit if statement in Python. There are no direct methods available for the same, so we use different methods in which we shift control to some other part of the program.

In the first method, we use the break statement to exit if statement in Python. The if statement is put within the while loop and program execution comes out of the loop when the break statement is encountered within the if statement.

In the second method, we use the return statement to exit if statement in Python. We put the if statement within a function and the return statement is used to exit the function when it is encountered.

We use the try and except statements in the final method and use exception-handling to exit if statement in Python. We manually raise an exception within the if statement to exit the statement and resume program execution.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 27 December

    Create Array of All NaN Values in Python

    Table of ContentsUsing numpy.empty() FunctionUsing numpy.full() FunctionUsing numpy.tile() FunctionUsing numpy.repeat() FunctionUsing Multiplication of numpy.ones() with nan Using numpy.empty() Function To create an array of all NaN values in Python: Use numpy.empty() to get an array of the given shape. Assign numpy.nan to every array element using the assignment operator (=). [crayon-63dab8280ef08001533287/] [crayon-63dab8280ef10113531192/] We used numpy.empty() […]

  • 27 December

    Call Function from Another Function in Python

    Table of ContentsCall a Function in PythonCall Function from Another Function in PythonCall a Function from Another Function within the Same/Different Classes Call a Function in Python To call a function in Python: Write a test() function, which prints a message. Call the function defined in the previous step. [crayon-63dab8280f122959739524/] [crayon-63dab8280f126982146435/] To call a function, […]

  • 27 December

    [Fixed] NameError Name ‘unicode’ is Not Defined in Python

    Table of ContentsUse str() MethodUse sys.version_info with strUse six.text_type Use str() Method To resolve the NameError: name 'unicode' is not defined, replace the occurrence of unicode() with str(). This issue occurs because unicode() was renamed to str() in Python 3. [crayon-63dab8280f285961163194/] [crayon-63dab8280f289113804269/] Unicode is a computing industry standard that ensures that text from most of […]

  • 26 December

    Repeat List N Times in Python

    Table of ContentsUsing the * operatorUsing the numpy.repeat() functionUsing the list comprehension techniqueUsing the itertools.repeat() functionConclusion This tutorial will demonstrate how to repeat list n times in Python. Using the * operator To repeat list n times in Python, use the * operator. Star operator(*) is used to multiply list by number e.g. lst*3 and […]

  • 26 December

    Get First Day of Next Month in Python

    Table of ContentsGet First Day of Next Month in PythonUsing the datetime.replace() with datetime.timedelta() functionUsing the calendar.monthrange() functionUsing the dateutil.relativedelta objectConclusion Get First Day of Next Month in Python This tutorial will demonstrate how to get first day of next month in Python. Using the datetime.replace() with datetime.timedelta() function To get first day of next […]

  • 25 December

    Convert String Array to Int Array in Python

    Table of ContentsUsing the for loop with int() functionUsing for loop with eval() functionUsing the map() with list() functionConclusion This tutorial will demonstrate how to convert string array to int array in Python. Using the for loop with int() function To convert string array to int array in Python: Use the for loop to loop […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.