Open In App

How to Break a Function in Python?

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Python
def fun(a):
    if a < 18:
        return "Underage"  # Terminate
    return "Eligible"  # Continue
print(fun(15))

Output
Underage

Explanation:

  • This function checks if the input a is less than 18. If true, it returns "Underage" and terminates the function.
  • As a is 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:

Python
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:

Python
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 ValueError with the message "Error" if b is 0.
  • This try block calls the function and the except block 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:

Python
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 a is less than 18, printing "Exiting."
  • Otherwise, it returns "Valid.".

Next Article
Article Tags :
Practice Tags :

Similar Reads