Break out of function in Python

In this post, we will see how to break out of function in Python.

Break out of function in Python

A function is a block of reusable code that can be called whenever required in a program. In Python, we can create functions using the def keyword. A function can return some value. This value is specified using the return statement. A function automatically ends when this statement is encountered.

We cannot use the break statement to break out of function in Python. The natural way to break out is by using the return statement only.

How to break out of function in Python?

Let us now discuss the methods to break out of function in Python.

Using the return statement to break out of function in Python

As discussed, the return statement is used to send some value back from the function. If this statement is missing then a None value is returned automatically.

The function ends automatically when a return is encountered, regardless of the code after the statement. We can use it to break out of function in Python.

See the code below.

Output:

Hello from the function

In the above example, we return a None value from the function. The print() function after the return statement is discarded and we break out of function in Python.

Using the try and except block to break out of function in Python

In Python, we use the try and except block to handle exceptions. If we have some code that can raise an exception, we put it in the try block. In the except block, we add an alternative code that will be executed in case an exception is raised.

Let us now discuss how we can use the try and except block to break out of function in Python. At the point from which we want to break out, we can add some code or use the raise statement to raise an exception.

When we execute the function, we do it inside the try block. So the code till the exception will run normally, and as soon as the exception is raised it will break out of the function and the code in the except block will execute.

We implement this logic in the code below.

Output:

Hello from the function
Exception raised

In the above example, the print(1/0) statement raises an exception and we break out of function in Python.

Using the sys.exit() function to break out of function in Python

This method can be thought of as a last resort. The sys.exit() function is used to end the python program. We can add this function to the point where we want to break out and the code will stop running.

For example,

Output:

Hello from the function
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0

Conclusion

To conclude, we discussed functions and how to break out of function in Python. Several methods were demonstrated. The most obvious answer is the return statement. It exits the function whenever it is encountered.

Another convenient method involved the use of the try and except block. The issue here is that we need to raise an exception to break out of function in Python. The final method involved terminating the program completely to break out of function using the sys.exit() function.

That’s all about how to break out of function in Python.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 29 June

    Get Day Name from Date in Python

    Table of ContentsUse the Calendar Module to Get the Name of the Day in PythonUse the strftime() Method to Get the Name of the Day in PythonUse Pandas Timestamp Method to Get the Name of the Day in PythonUse the weekday() Method to Get the Name of the Day in PythonUse the isoweekday() Method to […]

  • 27 June

    Fill Array with Random Numbers in Python

    Table of ContentsFill array with random numbers in PythonWays to fill array with random numbers in PythonUsing the numpy.random.randint() function to fill array with random numbers in PythonUsing the numpy.random.Generator.integers() function to fill array with random numbers in PythonUsing the random.randint() function to fill array with random numbers in PythonConclusionWas this post helpful? Fill array […]

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Check if Object Is Iterable in Python

    Table of ContentsWhat are iterables in Python?How to check if object is iterable in Python?Using the iter() function to check if object is iterable in PythonUsing the for loop to check if object is iterable in PythonUsing the isinstance() function to check if object is iterable in PythonConclusionWas this post helpful? In this post, we […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.