How to Exit an If Statement in Python

I was working on a project where I needed to stop executing code inside an if statement once a certain condition was met.

At first, I thought Python might have a direct “exit if” keyword, but it doesn’t. Instead, Python gives us multiple ways to exit an if block depending on whether we’re inside a loop, a function, or just running a script.

In this tutorial, I’ll share 7 simple methods I personally use to exit an if statement in Python. I’ll also give you full working code examples so you can try them directly.

Method 1: Use Python exit() Method

The exit() method is a built-in method in Python that is used to terminate the program execution immediately. This helps us stop the program when a condition is met without further processing.

Code:

age = 10
if age > 5:
    print("Condition met. Exiting...")
    exit()
print("This won't be printed.")

Output:

Condition met. Exiting...

You can refer to the screenshot below to see the output.

How to exit an if statement in Python

In this example, if the age exceeds 5, it will immediately exit an if statement using the exit() method.

Method 2: Use the Return Statement

The return statement in Python exits the function immediately, transferring control back to the caller. In this context, it effectively breaks out of the if statement, preventing the execution of code within the function.

Code

def check_age(age):
    if age < 18:
        print("You are under 18.")
        return
        print("It should not print this statement")
    print("You are 18 or older.")

check_age(15)

Output:

You are under 18.

You can refer to the screenshot below to see the output.

how to break out of if statement python

In this example, if the age is under 18, the function prints a message and immediately returns, skipping any further code execution within the function, so the statement “It should not print this statement” will not get printed.

Method 3: Use a Break Statement

The break statement in Python is used to exit prematurely from a loop. When encountered within an if clause, it immediately breaks out of the loop, regardless of any remaining iterations.

Code:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        print("Found 3. Exiting loop.")
        break
    print(num)

Output

1
2
Found 3. Exiting loop.

You can refer to the screenshot below to see the output.

How to exit an if clause

In this example, the loop iterates through the list of numbers in Python. When it encounters the value 3, the if clause triggers the break statement, causing an immediate exit from the Python loop.

Method 4: Use Try and Except Block

The try and except blocks are used for error handling in Python. Combined with an if statement, they can effectively exit the code block if an exception occurs.

In this context, if an error arises within the try block, the except block catches it and executes the specified actions, including exiting the Python program.

Code:

try:
    age = int(input("Enter a number: "))
    if age < 0:
        raise ValueError("Negative number entered.")
except ValueError as e:
    print("Error:", e)
    print("Exiting...")
    exit()
print("Number entered:",age)

In this example, the program attempts to convert user input into an integer within the try block in Python.

If the input is a negative number, a ValueError is raised, triggering the except block.

raise ValueError("Negative number entered.")

The program prints an error message inside the except block, exits gracefully, and terminates execution.

Output:

Enter a number: -5
Error: Negative number entered.
Exiting...

You can refer to the screenshot below to see the output.

how to exit a Python script in an if statement

If no error occurs, the program continues executing beyond the try-except block.

Method 5: Use Python’s sys.exit() Function

We use sys.exit() function to exit an if statement in Python. It can effectively break out of the block and terminate the program when called within an if statement.

Code:

import sys

def validate_input(user_input):
    if not user_input:
        print("No input provided. Exiting...")
        sys.exit()

user_input = input("Enter something: ")
validate_input(user_input)
print("Input validated:", user_input)

Output

Enter something: 
No input provided. Exiting...

You can refer to the screenshot below to see the output.

Python exit if statement

The program validates user input within the validate_input() function in this example. If no input is provided, the function prints an error message and calls sys.exit() to terminate the program immediately.

Method 6: Use quit() Function in Python

The quit() function is used to exit the Python interpreter. When called within an if statement, it effectively terminates the program execution, including any further code in the script.

This method provides a simple and direct way to exit the program when a specific condition is satisfied.

Code:

sales = 10000
if sales > 5000:
    print("Condition met. Exiting...")
    quit()
print("This won't be printed.")

In this example, if the sales exceed 5000, the program prints a message indicating that the condition is met and exits using the quit() function in Python.

Output

Condition met. Exiting...

You can refer to the screenshot below to see the output.

Python Breaking Out Of If Statement Inside

Consequently, the statement “This won’t be printed.” is not executed, ensuring an immediate exit from the program when the condition is satisfied.

How to Exit if Condition code os._exit() Function

The os._exit() function is used to exit the Python interpreter immediately. Unlike quit() or exit() functions, it performs no cleanup actions such as flushing buffers or executing cleanup handlers.

When called within an if statement in Python, it terminates the program without executing further code.

Code

import os

age = 10
if age > 5:
    print("Condition met. Exiting....")
    os._exit(0)
print("This won't be printed.")

In this example, if the age exceeds 5, the program prints a message indicating the condition is met and exits abruptly using os._exit(0) in Python.

Output

Condition met. Exiting....

You can refer to the screenshot below to see the output.

How to exit if condition code in Python

The statement “This won’t be printed.” is not executed, ensuring an immediate exit from the program when the condition is satisfied, without any further processing or cleanup.

This tutorial explored seven methods to exit an if statement in Python. Each method offers a unique approach to handling conditions and terminating program execution when necessary.

From the straightforward exit() method to the abrupt os._exit(), Python provides various tools to exit conditions gracefully or abruptly based on specific requirements.

Understanding these methods equips programmers with the flexibility to control program flow effectively and easily handle diverse scenarios.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.