The Return Type of a Function

Introduction

As is the case for a variable, a function has a type. The type of a function is the type of value the function must produce. Because Python is an inferred language, and it means that the compiler is equipped to figure out the type of value that a function is supposed to produce, you don't have to provide that information. Still you can if you want.

To indicate the type of value that a function is supposed to produce, after the closing parentheses of the function, type -> and the return type.

Practical LearningPractical Learning: Starting a Project

  1. Start Visual Studio Code
  2. Create a Python Application named TaxEvaluation3
  3. In the empty default module, type the following code to create three functions:
    def identify_employee():
        fname : str = ""
        lname : str = ""
    
        print("Employee Identification")
        fname = input("First Name:    ")
        lname = input("Last Name:     ")
    
        return fname + " " + lname
    
    def get_gross_salary():
        sal : float = 0.00
    
        sal = float(input("Gross Salary:  "))
    
        return sal

Returning a Known Type

If you want to indicate the type of value that a function produces, after its -> symbol, write that type.

Practical LearningPractical Learning: Starting a Project

  1. To indicate the returned types of some functions, change the code as follows:
    def identify_employee() -> str:
        fname : str = ""
        lname : str = ""
    
        print("Employee Identification")
        fname = input("First Name:    ")
        lname = input("Last Name:     ")
    
        return fname + " " + lname
    
    def get_gross_salary() -> float:
        sal : float = 0.00
    
        sal = float(input("Gross Salary:  "))
    
        return sal
  2. To enhance your code, change the document as follows:
    def identify_employee() -> str:
        fname : str = ""
        lname : str = ""
    
        print("Employee Identification")
        fname = input("First Name:    ")
        lname = input("Last Name:     ")
    
        return fname + " " + lname
    
    def get_gross_salary() -> float:
        sal : float = 0.00
    
        sal = float(input("Gross Salary:  "))
    
        return sal
    
    def evaluate_tax():
        print("============================================")
        print("\t - Idaho - State Income Tax -")
        print("============================================")
    
        added_amount  : float
        tax_rate      : float
        gross_salary  : float 
    
        print("Enter the information for tax preparation")
        employee : str = identify_employee()
        gross_salary  : float = get_gross_salary()
    
        if gross_salary >= 11_760:
            tax_rate = 6.925
            added_amount = 543.90
        if gross_salary < 11_760:
            tax_rate = 6.625
            added_amount = 284.20
        if gross_salary < 7_840:
            tax_rate = 5.625
            added_amount = 196.00
        if gross_salary < 6_272:
            tax_rate = 4.625
            added_amount = 123.48
        if gross_salary < 4_704:
            tax_rate = 3.625
            added_amount = 66.64
        if gross_salary < 3_136:
            tax_rate = 3.125
            added_amount = 17.64
        if gross_salary < 1_568:
            tax_rate = 1.125
            added_amount = 0
    
        tax_amount = added_amount + (gross_salary * tax_rate / 100.00)
        net_pay = gross_salary - tax_amount
        present(employee, gross_salary, tax_rate, added_amount, tax_amount, net_pay)
    
    def present(staff, gross_salary, tax_rate, added_amount, tax_amount, net_pay):
        print("============================================")
        print("\t- Idaho - State Income Tax -")
        print("============================================")
        print("Employee Information")
        print(f"Employee Name: {staff}")
        print("============================================")
        print("Tax Information")
        print("--------------------------------------------")
        print(f"Gross Salary:    {gross_salary:7.2f}")
        print(f"Tax Rate:        {tax_rate}%")
        print(f"Amount Added:  {added_amount:7.2f}")
        print(f"Tax Amount:    {tax_amount:7.2f}")
        print(f"Net Pay:         {net_pay:7.2f}")
    
    evaluate_tax()
    print("===========================================")
  3. To execute, on the main menu, click Run -> Run Without Debugging
  4. For the First Name, type Lucinda and press Enter
  5. For the Last Name, type Matthews and press Enter
  6. For the Gross Salary, type 2258.97 and press Enter
    ============================================
        - Idaho - State Income Tax -
    ============================================
    Enter the information for tax preparation
    Employee Identification
    First Name:    Lucinda
    Last Name:     Matthews
    Gross Salary:  2258.97
    ============================================
       - Idaho - State Income Tax -
    ============================================
    Employee Information
    Employee Name: Lucinda Matthews
    ============================================
    Tax Information
    --------------------------------------------
    Gross Salary:  2258.97
    Tax Rate:         3.125%
    Amount Added:    17.64
    Tax Amount:      88.23
    Net Pay:       2170.74
    ===========================================
    Press any key to continue . . .
  7. To execute again, on the main menu, click Run -> Run Without Debugging
  8. For the First Name, type Matthew and press Enter
  9. For the Last Name, type Robertson and press Enter
  10. For the Gross Salary, type 6412.46 and press Enter
    ============================================
        - Idaho - State Income Tax -
    ============================================
    Enter the information for tax preparation
    Employee Identification
    First Name:    Matthew
    Last Name:     Robertson
    Gross Salary:  6412.46
    ============================================
       - Idaho - State Income Tax -
    ============================================
    Employee Information
    Employee Name: Matthew Robertson
    ============================================
    Tax Information
    --------------------------------------------
    Gross Salary:  6412.46
    Tax Rate:         5.625%
    Amount Added:   196.00
    Tax Amount:     556.70
    Net Pay:       5855.76
    ===========================================
    Press any key to continue . . .

Named Arguments

Introduction

We already know that you can create a function that takes one parameter, and we know how to call such a function. Here is an example we saw already:

def send_message(msg):
    print(msg)

send_message("Please remember to submit your time sheet.")

As an option, to be more precise when calling a function and passing an argument, provide the name of the parameter and assign the desired value to it. Here is an example:

def send_message(msg):
    print(msg)

send_message(msg = "Please remember to submit your time sheet.")

In the same way, if you have a function that uses more than one parameter, when calling the function, you can type the name of each parameter and assign the desired value to it. Here is an example:

def describe(name, price):
    print("Item Name:    ", name)
    print("Marked Price: ", price)

print("Fun Department Store")
print("-----------------------------------------------------------")
describe(name = "Men's Alpha Tapered-Fit Stretch Chino Pants", price = 74.95)
print("===========================================================")

One of the wonderful characteristics about this feature is that you can pass the arguments in any order as long as you provide a name for each argument.

Requiring a Named Argument

By default, you have the option of naming or not naming an argument when calling a function. If you want to require that, every time the function is called, the name of a parameter must be specified, pass the first argument as * followed by a comma. As a result, the following code will produce an error:

def send_message(*, msg):
    print(msg)

send_message("Please remember to submit your time sheet.")
print("===========================================")

Of course, to solve the problem, you must name the argument when calling the function. In the same way, if you want all arguments of a function to be named when calling a function, start their section with * and a comma. Here is an example:

def send_message(*, year, makeModel, value):
    print("Vehicle:      ", year, makeModel)
    print("Market Value: ", value)

send_message(makeModel="Chevrolet Equinox", value=25800, year=2022)
print("===========================================")

This would produce:

Vehicle:       2022   Chevrolet Equinox
Market Value:  25800
===========================================
Press any key to continue . . .

If you want to require names for some arguments and not for other arguments, in the parentheses of the function you are creating, type *,. On the left side of *,, put the parameter(s) whose name(s) will not be required. On the right side of *,, put the parameters whose names will be required. When calling the function, the values of the unnamed arguments must be given in the exact order their parameters appear in the function. The other arguments, that must be named, can appear in any order. Here is an example:

def send_message(gasCity, color, gasHighway, *, year, makeModel, value):
    print("Vehicle:          ", year, makeModel)
    print("MPG City/Highway: ", gasCity, "/", gasHighway)
    print("Market Value:     ", value)

send_message(26, "Blue", 31, makeModel="Chevrolet Equinox", value=25800, year=2022)
print("===========================================")

This would produce:

Vehicle:           2022 Chevrolet Equinox
MPG City/Highway:  26 / 31
Market Value:      25800
===========================================
Press any key to continue . . .

Naming the Arguments

Earlier, we saw that, if you create a function that uses many parameters, when calling the function, you must pass the arguments in the appropriate order. If you pass the arguments in the wrong order, you will receive an error.

To pass the arguments in the order of your choice, you can use the names that were given to them in the function definition. To do that, in the parentheses of the function call, write the name of a parameter and assign the desired value to it. Do the same for each parameter. Separate them with commas. Here are two examples:

def getFullName(itemNbr, itemName, size, price):
    print("Item #:       ", itemNbr)
    print("Name:         ", itemName)
    print("Size:         ", size)
    print("Marked Price: ", price)

getFullName(size='M', price=124.95, itemNbr=972947, itemName="Balloon-Sleeve Wrap Midi Dress")
print("------------------------------------------------------------")
getFullName(itemName="Men's Infinite Stretch Solid Slim-Fit Pants", itemNbr=240_585, price=72.50, size="34x30")
print("============================================================")

This would produce:

============================================================
Item #:        972947
Name:          Balloon-Sleeve Wrap Midi Dress
Size:          M
Marked Price:  124.95
------------------------------------------------------------
Item #:        240585
Name:          Men's Infinite Stretch Solid Slim-Fit Pants
Size:          34x30
Marked Price:  72.5
============================================================
Press any key to continue . . .

Default Arguments

Introduction

Consider the following code:

def price_evaluation(discountRate):
markedPrice = 125.00
discountedPrice = markedPrice * discountRate / 100;
finalPrice = markedPrice - discountedPrice;

print("Marked Price:     ", markedPrice)
print("Discount Rate:    ", discountRate)
print("Discounted Price: ", discountedPrice)
print("Final Price:      ", finalPrice)

print("==================================")
print("Fun Department Store")
print("==================================")
price_evaluation(25)
print("-------------------------")
price_evaluation(15)
print("-------------------------")
price_evaluation(25)
print("-------------------------")
price_evaluation(35)
print("-------------------------")
price_evaluation(25)
print("==================================");

This would produce:

==================================
Fun Department Store
==================================
Marked Price:      125.0
Discount Rate:     25
Discounted Price:  31.25
Final Price:       93.75
-------------------------
Marked Price:      125.0
Discount Rate:     15
Discounted Price:  18.75
Final Price:       106.25
-------------------------
Marked Price:      125.0
Discount Rate:     25
Discounted Price:  31.25
Final Price:       93.75
-------------------------
Marked Price:      125.0
Discount Rate:     35
Discounted Price:  43.75
Final Price:       81.25
-------------------------
Marked Price:      125.0
Discount Rate:     25
Discounted Price:  31.25
Final Price:       93.75
==================================
Press any key to continue . . .

In some applications, almost every time you call a certain function, you usually pass the same value, in which case you pass a different value only sometimes. In this type of scenario, you can provide a default value to the parameter so that you would pass an argument only when it is different from the default value.

When creating a function whose parameter is passed with the same value almost every time, in the parentheses of the function, assign the desired default value to the parameter. Here is an example:

def price_evaluation(discountRate = 25):
# . . .

After doing this, whenever you call the function, if you want to pass the argument with the default value, you can omit it. If you call the function without the argument, the function would use the default value. Here are examples:

def price_evaluation(discountRate = 25):
markedPrice = 125.00
discountedPrice = markedPrice * discountRate / 100;
finalPrice = markedPrice - discountedPrice;

print("Marked Price:     ", markedPrice)
print("Discount Rate:    ", discountRate)
print("Discounted Price: ", discountedPrice)
print("Final Price:      ", finalPrice)

print("==================================")
print("Fun Department Store")
print("==================================")
price_evaluation()
print("-------------------------")
price_evaluation(15)
print("-------------------------")
price_evaluation()
print("-------------------------")
price_evaluation(35)
print("-------------------------")
price_evaluation()
print("==================================")

Mixing Default arguments and Others

You can create a function that uses a mix of parameters that use default values or not. If you create a function that uses two parameters with only one with a default value, the parameter without a default value must come first. In the body of the function, you can ignore or use the parameters as you see fit. Here is an example:

def price_evaluation(markedPrice, discountRate = 25):
discountedPrice = markedPrice * discountRate / 100;
finalPrice = markedPrice - discountedPrice;

print("Marked Price:     ", markedPrice)
print("Discount Rate:    ", discountRate)
print("Discounted Price: ", discountedPrice)
print("Final Price:      ", finalPrice)

When calling the function, you must provide at least a value for the parameter that doesn't use a default parameter. In this case, the function would use the default value for the other parameter. Still, if you want, you can pass a value for the default argument. Here are examples:

def price_evaluation(markedPrice, discountRate = 25):
discountedPrice = markedPrice * discountRate / 100;
finalPrice = markedPrice - discountedPrice;

print("Marked Price:     ", markedPrice)
print("Discount Rate:    ", discountRate)
print("Discounted Price: ", discountedPrice)
print("Final Price:      ", finalPrice)

print("==================================")
print("Fun Department Store")
print("==================================")
price_evaluation(125.00)
print("-------------------------")
price_evaluation(125.00, 15)
print("-------------------------")
price_evaluation(245.85)
print("-------------------------")
price_evaluation(245.85, 35)
print("==================================")

This would produce:

==================================
Fun Department Store
==================================
Marked Price:      125.0
Discount Rate:     25
Discounted Price:  31.25
Final Price:       93.75
-------------------------
Marked Price:      125.0
Discount Rate:     15
Discounted Price:  18.75
Final Price:       106.25
-------------------------
Marked Price:      245.85
Discount Rate:     25
Discounted Price:  61.4625
Final Price:       184.3875
-------------------------
Marked Price:      245.85
Discount Rate:     35
Discounted Price:  86.0475
Final Price:       159.8025
==================================
Press any key to continue . . .

If you want to create a function that uses three or more parameters with one of them having a default value, in the parentheses of the function, the parameter without a default value must come first. When calling the function, you must provide a value for each of the parameters that don't use default values. Here is an example:

def price_evaluation(itemName, markedPrice, discountRate = 25):
discountedPrice = markedPrice * discountRate / 100;
finalPrice = markedPrice - discountedPrice;

print("Item Name:        ", itemName)
print("Marked Price:     ", markedPrice)
print("Discount Rate:    ", discountRate)
print("Discounted Price: ", discountedPrice)
print("Final Price:      ", finalPrice)

print("===========================================================================")
print("Fun Department Store")
print("===========================================================================")
price_evaluation("Khaki Pants", 45.50)
print("---------------------------------------------------------------------------")
price_evaluation("Women's Croft & Barrow® Print Twist-Front Midi Dress", 88.55, 15)
print("---------------------------------------------------------------------------")
price_evaluation("Everyday Straight Jeans in Regular, Slim & Husky", 22.25)
print("---------------------------------------------------------------------------")
price_evaluation("Women's Leather High Heels", 115.75, 35)
print("===========================================================================")

This would produce:

===========================================================================
Fun Department Store
===========================================================================
Item Name:         Khaki Pants
Marked Price:      45.5
Discount Rate:     25
Discounted Price:  11.375
Final Price:       34.125
---------------------------------------------------------------------------
Item Name:         Women's Croft & Barrow® Print Twist-Front Midi Dress
Marked Price:      88.55
Discount Rate:     15
Discounted Price:  13.2825
Final Price:       75.2675
---------------------------------------------------------------------------
Item Name:         Everyday Straight Jeans in Regular, Slim & Husky
Marked Price:      22.25
Discount Rate:     25
Discounted Price:  5.5625
Final Price:       16.6875
---------------------------------------------------------------------------
Item Name:         Women's Leather High Heels
Marked Price:      115.75
Discount Rate:     35
Discounted Price:  40.5125
Final Price:       75.2375
===========================================================================
Press any key to continue . . .

Using Many Default Arguments

If you are creating a function with three parameters with two of them with default values, in the parentheses, the parameter without the default value must come first. Here is an example:

def price_evaluation(origPrice, discountRate = 25, taxRate = 7.25):
. . .

When calling the function, you can pass just one argument, in which case, the function would use the default values of the second parameters. If you call the function with two arguments, the values would be used for the first and the second parameter. Otherwise, you can call the function with all three parameters. Here are examples:

def price_evaluation(origPrice, discountRate = 25, taxRate = 7.25):
discountAmount     = origPrice * discountRate / 100;
priceAfterDiscount = origPrice - discountAmount;
taxAmount          = priceAfterDiscount * taxRate / 100;
finalPrice         = priceAfterDiscount - taxAmount;

print("Original Price:       ", origPrice)
print("Discount Rate:        ", discountRate)
print("Discount Amount:      ", discountAmount)
print("Price after Discount: ", priceAfterDiscount)
print("Tax Rate:             ", taxRate)
print("Tax Amount:           ", taxAmount)
print("Final Price:          ", finalPrice)

print("=========================================")
print("Fun Department Store")
print("=========================================")
price_evaluation(45.50)
print("-----------------------------------------")
price_evaluation(88.55, 15)
print("-----------------------------------------")
price_evaluation(225.25, 50, 5.75)
print("=========================================")

Thi would produce:

=========================================
Fun Department Store
=========================================
Original Price:        45.5
Discount Rate:         25
Discount Amount:       11.375
Price after Discount:  34.125
Tax Rate:              7.25
Tax Amount:            2.4740625
Final Price:           31.6509375
-----------------------------------------
Original Price:        88.55
Discount Rate:         15
Discount Amount:       13.2825
Price after Discount:  75.2675
Tax Rate:              7.25
Tax Amount:            5.456893750000001
Final Price:           69.81060624999999
-----------------------------------------
Original Price:        225.25
Discount Rate:         50
Discount Amount:       112.625
Price after Discount:  112.625
Tax Rate:              5.75
Tax Amount:            6.4759375
Final Price:           106.1490625
=========================================
Press any key to continue . . .

The real rule is that if you are creating a function with many parameters with some parameters having default values, in the parentheses, the parameters without the default values must come first.

As seen in the section about named arguments, if you are calling a function that has one or more default arguments, you can use the name of each parameter when calling the function. This means that if you provide a name for an argument, you must specify the name of each argument whose value you provide. Here are examples:

print("============================================================")
def price_evaluation(origPrice, discountRate = 25, taxRate = 7.25):
discountAmount     = origPrice * discountRate / 100;
priceAfterDiscount = origPrice - discountAmount;
taxAmount          = priceAfterDiscount * taxRate / 100;
finalPrice         = priceAfterDiscount - taxAmount;

print("Original Price:       ", origPrice)
print("Discount Rate:        ", discountRate)
print("Discount Amount:      ", discountAmount)
print("Price after Discount: ", priceAfterDiscount)
print("Tax Rate:             ", taxRate)
print("Tax Amount:           ", taxAmount)
print("Final Price:          ", finalPrice)

print("=========================================")
print("Fun Department Store")
print("=========================================")
price_evaluation(origPrice=45.50)
print("-----------------------------------------")
price_evaluation(discountRate = 15, origPrice=88.55)
print("-----------------------------------------")
price_evaluation(origPrice=225.25, taxRate = 5.75, discountRate = 50)
print("=========================================")

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2021-2024, FunctionX Friday 31 December 2021 Next