In Python, breaking a function allows us to exit from loops within the function. With the help of the return statement and the break keyword, we can control the flow of the loop.
Using return keyword
This statement immediately terminates a function and optionally returns a value. Once return is executed, any code after it is ignored and the function exits at that point.
Example:
def fun(a):
if a < 18:
return "Underage" # Terminate
return "Eligible" # Continue
print(fun(15))
Output
Underage
Explanation:
- This function checks if the input
ais less than 18. If true, it returns"Underage"and terminates the function. - As
ais 18 or more, it returns"Eligible", indicating the function continues normally.
Common Methods to break a Function
In Python, we use the "break" and "return" statements to exit a function. However, there are other ways to manage flow control or exit from a function, depending on the situation.
Let's explore these methods in detail, one by one.
Using break keyword
break statement exits a loop early but allows the function to continue after the loop. It is generally used in for and while loops.
Example:
def fun(no):
for i in no:
if i % 2 == 0:
print(i) # Found
break
else:
print("Not Found") # Not found
# input
fun([1, 3, 5, 8, 7])
Output
8
Explanation:
- This function finds the first even number in the list, prints it and exits the loop.
- If no even number is found, it prints
"Not Found".
using raise keyword
raise statement exits the function by raising an exception, stopping the normal flow and passing the error.
Example:
def fun(a, b):
if b == 0:
raise ValueError("Error") # Error
return a / b # Output
# Input
try:
print(fun(10, 0)) # Will raise an exception
except ValueError as e:
print(e) # Error
Output
Error
Explanation:
- This function raises a
ValueErrorwith the message"Error"ifbis 0. - This
tryblock calls the function and theexceptblock prints the error message when caught.
using sys.exit()
sys.exit() function terminates the entire program, not just the function and is typically used to end a script under specific conditions.
Example:
import sys
def fun(a):
if a < 18:
print("Exiting") # Exit
sys.exit()
return "Valid." # Valid
# Input
fun(15)
Output
Exiting
Explanation:
- This function exits the program if
ais less than 18, printing "Exiting." - Otherwise, it returns
"Valid.".