Programming Essentials Python - User Defined Functions - Returning Variables

Let us understand more about returning values to the caller.

  • We typically have one or more return statements inside the function body.

  • The statement return exits a function, we can return back an expression or variable or object to the caller. A return statement with no expression is the same as return None.

  • If there is no return statement in the function body then the function returns None object.

  • We can return multiple expressions in Python.

def get_commission_amount(sales_amount, commission_pct):
    """Function to compute commission amount. commission_pct should be passed as percent notation (eg: 20%)
    20% using percent notation is equal to 0.20 in decimal notation.
    commission_amount = (sales_amount * commission_pct / 100) if commission_pct else 0
    return commission_amount

get_commission_amount(1000, 20)
def get_phone_count(employee_id: int, phone_numbers: list):
    valid_count = 0
    invalid_count = 0

    for phone_number in phone_numbers:
        if len(phone_number) != 10:
            invalid_count += 1
            valid_count += 1

    return valid_count, invalid_count

get_phone_count(1, ['1234567890', '245 789 1234', '+1 156 290 1489'])

Watch the video tutorial here