How To Exit A Function In Python

You will learn here how to exit a function in Python. In Python, you can exit a function using the return statement. The return statement allows you to specify a value or expression to be returned from the function to the calling code.

When the return statement is executed, the function exits immediately and returns the specified value or expression to the calling code.

Here is an example of a function that returns the square of a number and exits immediately if the input is negative:

def square(num):
    if num < 0:
        print("Error: Negative input")
        return   # exit the function immediately
    return num**2

In this example, the function square takes a single argument num. If num is negative, the function prints an error message and exits immediately using the return statement with no value. If num is non-negative, the function calculates and returns the square of num.

See also  How to Convert Int to Binary in Python?

You can also use the return statement with a value to exit a function and return a value to the calling code. Here is an example of a function that returns the sum of two numbers and exits immediately if either input is not a number:

def add(num1, num2):
    if not isinstance(num1, (int, float)) or not isinstance(num2, (int, float)):
        print("Error: Invalid input")
        return None   # exit the function and return None
    return num1 + num2

In this example, the function add takes two arguments num1 and num2. If either num1 or num2 is not a number, the function prints an error message and exits immediately using the return statement with a value of None. If both inputs are valid numbers, the function calculates and returns the sum of num1 and num2.

See also  Python for Ethical Hacking: Basics to Advanced

You can exit a function in Python using the return statement. By specifying a value or expression to be returned, you can also pass information back to the calling code. By using conditional statements and appropriate error handling, you can create functions that exit gracefully when input is invalid or unexpected.