Skip to content

Python exit if statement

  • by

Thebreak statement is used when you want to break out of loops, not if statements. You can have another if statement that exits on logic in Python.

Python exit if statement

A simple example code exit an if Statement With break in Python.

for i in range(10):
    print(i)
    if i == 3:
        print("Exit if statement")
        break

Output:

Python exit if statement

Wrap the code in its function. Instead of break, use return.

def some_function():
    if condition_a:
        # do something and return early
        ...
        return
    ...
    if condition_b:
        # do something else and return early
        ...
        return
    ...
    return

if outer_condition:
    ...
    some_function()
    ...

Python Break out of if statement in for loop in if statement

if (status_code == 410):
    s_list = ['String A', 'String B', 'String C']
    for x in in s_list:
        if (some condition):
            print(x)
            break
    else:
        print('Not Found')

print will only be called if the for the loop is terminated by a StopIteration exception while iterating over s_list, not if it is terminated by the break statement.

Note: Using exit() abruptly terminates the entire program. In some cases, it might be better to use other control flow mechanisms, such as raising an exception, to handle errors or unexpected conditions more gracefully.

Comment if you have any doubts or suggestions on this Python if statement topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading