How to Exit from if Statements in Python
This guide explains how to control the flow of execution within and around if statements in Python. We'll cover exiting if blocks, exiting functions containing if statements, and exiting loops that contain if statements. We'll focus on using return, break, raise (with try/except), if/elif/else chains, and briefly touch on sys.exit() with a strong caution.
Exiting an if Block (and Function) with return
The return statement immediately exits the current function, and therefore also exits any if statement within that function. This is the standard way to exit an if block and the containing function simultaneously.
def my_function(num):
if num > 0:
print('num > 0')
return # Exits the if AND the function
if num < 0:
print('num < 0')
return # Exits the if AND the function
print('num = 0')
return
my_function(100) # Output: num > 0
my_function(-30) # Output: num < 0
my_function(0) # Output: num = 0
returnwithout a value implicitly returnsNone.- Any code after a
returnstatement within that function's scope will not be executed. - You can also return specific values based on condition.
def my_function(num):
if num > 0:
print('num > 0')
return 'A'
if num < 0:
print('num < 0')
return 'B'
print('num = 0')
return 'C'
result = my_function(100)
print(result) # Output: A
result = my_function(-30)
print(result) # Output: B
result = my_function(0)
print(result) # Output: C
Exiting an if Block and Loop with break
The break statement exits the innermost enclosing loop (for or while), also exiting any if statement within that loop.
for i in range(1, 7):
print(i) # Prints 1, then 2, then 3
if i == 3:
print(i) # Prints 3
break # Exits the if AND the for loop
if i == 6: # This will never run in this case
print(i)
break
Output
1
2
3
3
You can also use it with a while loop.
num = 6
while num > 0:
if num % 2 == 0:
num = num - 10
break # Exit the while loop and the if statement
if num % 3 == 0: # Never runs as previous condition is always met first
num = num - 20
break
break # Always executes if the loop starts
print(num) # Output: -4
Exiting with raise and try/except
The raise keyword throws an exception. This immediately stops execution of the current block of code (including any if statement) and propagates the exception up the call stack. You must use a try/except block to handle raised exceptions, or your program will terminate.
num = 6
try:
if num % 2 == 0:
print('Number is divisible by 2')
raise ValueError('some error') # Exit if AND raise exception
print('This will not run')
except ValueError:
print('Except block runs') # Output: Except block runs
- In this case an exception is raised, so the except block is executed.
- If you don't know the type of exceptions that may be raised, use the generic
Exceptionclass.
def example():
a = 123
raise ValueError('invalid value')
try:
example()
except Exception as e:
print('A ValueError occurred...', e) # Output: A ValueError occurred... invalid value
Using if/elif/else for Multiple Conditions
Often, you don't want to exit, but rather handle different conditions sequentially. Use if/elif/else for this:
num = 9
if num > 10:
print('num > 10')
elif num > 9:
print('num > 9') # This won't run, because 9 is not > 10
elif num > 8:
print('num > 8') # Output: num > 8 (this runs)
else:
print('else block runs')
- The
if,elif, andelseblocks provide a structured way to handle different cases without prematurely exiting.
Exiting the Program with sys.exit() (Use with Caution)
The sys.exit() function terminates the entire Python script. This should generally be used sparingly, as it's a very abrupt way to end program execution. It should only be used at the end of the script, and other exit methods described above are recommended.
import sys
num = 9
if num == 9:
print('num > 10')
sys.exit() # Exits the ENTIRE script
print('This never runs')
Avoid overusing sys.exit(). It's generally better to structure your code with return, break, and exception handling to control program flow. sys.exit() should be reserved for situations where the program can not continue, such as unrecoverable errors or reaching a deliberate termination point.