. Advertisement .
. Advertisement .
How to exit the if statement in Python when you don’t want to use it? This tutorial will help you end the loop and exit a function in Python in some particular ways.
What Is The If Statement In Python?
The If statement in python is used for decision making. Its body shows the indentation with the first unidented marks at the end. The program will evaluate the test expression and decide whether the expression is True.
If the result is True, it will execute the statement. On the reverse, with the False result, the statements will not be executed.
number1 = 18 if number1 > 0: print(number1, "is a positive number.") print("This is always printed.") number1 = -56 if number1 < 0: print(number1, "is a negative number.") print("This is also always printed.")
18 is a positive number. This is always printed. -56 is a negative number. This is also always printed.
Example of an if…else statement.
Program checks if the number is positive or negative and displays an appropriate message.
number2 = -1989 if number2 >= 0: print(number2,"is positive number or Zero") else: print(number2,"is a negative number")
-1989 is a negative number
How To Exit The if Statement In Python
Method 1: Use The break Function In Python
The break statement is a common method to exit the if statement. It jumps out of the loop directly in a specified condition. The main purpose of this is to move our program’s control flow outside a current loop. Here is a common model:
conditions = [True, False] some_condition = True for condition_a in conditions: for condition_b in conditions: print (“/n”) print (“with condition_a”, condition_a) print (“with condition_b”, condition_b) while (True): if (some_condition): print ("checkpoint 1") if (condition_a): # Do something and then exit the outer if block print("checkpoint 2") break print ("checkpoint 3") if (condition_b): # Do something and then exit the outer if block print("checkpoint 4") break print ("checkpoint 5") # More code here make sure it is looped once break
For example, let’s set the range around 15 and exit the if statement at number 5.
for x in range(15): print(x) if x == 5: break
0 1 2 3 4 5
However, this method is only available to use outside a nested if statement. The below example shows how it happens inside an nested one:
a = 0 if a%2 == 0: if a == 0: break if a > 0: print("Even") print("Broken")
File "code.py", line 5 break ^^^^^ SyntaxError: 'break' outside loop
Method 2: Use Return Command
The return command is ideal for any nested loop or construct that you cannot break easily.
def function(num): if num%2 == 0: if num == 0: return if num > 0: print("Even") if __name__ == "__main__": function(88) print("Broken out")
Even Broken out
There are two methods to exit the if statement in Python. The return option will solve your problem in a few seconds so consider trying it.
Leave a comment