﻿ Lesson 21: Lists and Functions

Fundamentals of Functions

Introduction

Lists and functions can be mixed in various way. The primary way involve a list and a function is to create a list in the body of a function. Such a list is used like any of the lists we have used so far. Practical Learning: Introducing Loops

1. Start Visual Studio Code
2. On the main menu, click File -> New File
3. Click the Select A Language link
4. Scroll down in the list of languages and click Python (python)
5. In the empty document,type the following lines:
```def create():
print("===================================================================")
print("Machine Depreciation Evaluation - Straight-Line Method")
print("===================================================================")

estimated_life : int   = 0
machine_cost   : float = 0
salvage_value  : float = 0

book_values               = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
accumulated_depreciations = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

print("Enter value to calculate the depreciation of a machine over a certain period of time, using the Straight-Line Method")
machine_cost   = float(input("Machine Cost:   "))
salvage_value  = float(input("Salvage Value:  "))
estimated_life = int(input("Estimated Life: "))

yearly_depreciation = (machine_cost - salvage_value) / estimated_life

book_value_year0  = machine_cost

i : int = 0

while i < estimated_life:
book_values[i]               = machine_cost - (yearly_depreciation * (i + 1))
accumulated_depreciations[i] = yearly_depreciation * (i + 1)
i = i + 1

i = 0

print("===================================================================")
print("Machine Depreciation Evaluation - Straight-Line Method")
print("===================================================================")
print(F"Machine Cost:\t\t{machine_cost:6.2f}")
print("-------------------------------------------------------------------")
print(F"Salvage Calue:\t\t{salvage_value:6.2f}")
print("-------------------------------------------------------------------")
print(F"Estimated Life:\t\t{estimated_life:6.0f} years")
print("-------------------------------------------------------------------")
print(F"Yearly Depreciation:\t{yearly_depreciation:6.2f}/year")
print("-------------------------------------------------------------------")
print(F"Monthly Depreciation:\t{(yearly_depreciation / 12):6.2f}/month")
print("=====+=====================+============+==========================")
print("Year | Yearly Depreciation | Book Value | Accumulated Depreciation")
print("-----+---------------------+------------+--------------------------")
print(F" 0   |\t\t           |{book_value_year0:10.2f}  |")
print("-----+---------------------+------------+--------------------------")

while i < estimated_life:
print(F" {i + 1}   |\t{yearly_depreciation:12.2f}       |{book_values[i]:10.2f}  |\t{accumulated_depreciations[i]:10.2f}")
print("-----+---------------------+------------+--------------------------")
i = i + 1

create()```
6. To save the document, on the main menu, click File -> Save
7. Select a folder of your choice or create one and select it in the top combo box of the dialog box
8. Change the File Name to Exercise19
9. Click Save
10. To execute the application and test it, on the main menu, click Run -> Run Without Debugging
11. In the Terminal, click the right side of Machine Cost, type 16244.65 and press Enter
12. For the Salvage Value, type 825.35 and press Enter
13. For the Estimated Life, type 8 and press Enter
```===================================================================
Machine Depreciation Evaluation - Straight-Line Method
===================================================================
Enter value to calculate the depreciation of a machine over a certain period of time, using the Straight-Line Method
Machine Cost:   16244.65
Salvage Value:  825.35
Estimated Life: 8
===================================================================
Machine Depreciation Evaluation - Straight-Line Method
===================================================================
Machine Cost:           16244.65
-------------------------------------------------------------------
Salvage Calue:          825.35
-------------------------------------------------------------------
Estimated Life:              8 years
-------------------------------------------------------------------
Yearly Depreciation:    1927.41/year
-------------------------------------------------------------------
Monthly Depreciation:   160.62/month
=====+=====================+============+==========================
Year | Yearly Depreciation | Book Value | Accumulated Depreciation
-----+---------------------+------------+--------------------------
0   |                     |  16244.65  |
-----+---------------------+------------+--------------------------
1   |       1927.41       |  14317.24  |          1927.41
-----+---------------------+------------+--------------------------
2   |       1927.41       |  12389.83  |          3854.82
-----+---------------------+------------+--------------------------
3   |       1927.41       |  10462.41  |          5782.24
-----+---------------------+------------+--------------------------
4   |       1927.41       |   8535.00  |          7709.65
-----+---------------------+------------+--------------------------
5   |       1927.41       |   6607.59  |          9637.06
-----+---------------------+------------+--------------------------
6   |       1927.41       |   4680.18  |         11564.47
-----+---------------------+------------+--------------------------
7   |       1927.41       |   2752.76  |         13491.89
-----+---------------------+------------+--------------------------
8   |       1927.41       |    825.35  |         15419.30
-----+---------------------+------------+--------------------------```

Returning a List

Just like a function can return a regular value, a function can produce a list. To make this happen, you can create a simple list in the body of the function. You can also request values from the user and create a list from them. You can also use arguments passed to the function, use those arguments or perform operations on them to get some values for a list you would create. Once the list is ready, you can use the return keyword to return the list from the function. Practical Learning: Introducing Loops

1. Change the document as follows:
```def generateBookValues(cost, salvage, life, deprec):
book_values               = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
i : int = 0

while i < life:
book_values[i] = cost - (deprec * (i + 1))
i = i + 1

return book_values

def accumulate(cost, salvage, life, deprec):
accumulations = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

i : int = 0

while i < life:
accumulations[i] = deprec * (i + 1)
i = i + 1

return accumulations

print("===================================================================")
print("Machine Depreciation Evaluation - Straight-Line Method")
print("===================================================================")

estimated_life : int   = 0
machine_cost   : float = 0
salvage_value  : float = 0

print("Enter value to calculate the depreciation of a machine over a certain period of time, using the Straight-Line Method")
machine_cost   = float(input("Machine Cost:   "))
salvage_value  = float(input("Salvage Value:  "))
estimated_life = int(input("Estimated Life: "))

yearly_depreciation = (machine_cost - salvage_value) / estimated_life
book_value_year0  = machine_cost

book_values = generateBookValues(machine_cost, salvage_value, estimated_life, yearly_depreciation)
accumulated_depreciations = accumulate(machine_cost, salvage_value, estimated_life, yearly_depreciation)

i : int = 0

print("===================================================================")
print("Machine Depreciation Evaluation - Straight-Line Method")
print("===================================================================")
print(F"Machine Cost:\t\t{machine_cost:6.2f}")
print("-------------------------------------------------------------------")
print(F"Salvage Calue:\t\t{salvage_value:6.2f}")
print("-------------------------------------------------------------------")
print(F"Estimated Life:\t\t{estimated_life:6.0f} years")
print("-------------------------------------------------------------------")
print(F"Yearly Depreciation:\t{yearly_depreciation:6.2f}/year")
print("-------------------------------------------------------------------")
print(F"Monthly Depreciation:\t{(yearly_depreciation / 12):6.2f}/month")
print("=====+=====================+============+==========================")
print("Year | Yearly Depreciation | Book Value | Accumulated Depreciation")
print("-----+---------------------+------------+--------------------------")
print(F" 0   |\t\t           |{book_value_year0:10.2f}  |")
print("-----+---------------------+------------+--------------------------")

while i < estimated_life:
print(F" {i + 1}   |\t{yearly_depreciation:12.2f}       |{book_values[i]:10.2f}  |\t{accumulated_depreciations[i]:10.2f}")
print("-----+---------------------+------------+--------------------------")
i = i + 1

```
2. To execute the application, on the main menu, click Run -> Run Without Debugging
3. In the Terminal, click the right side of Machine Cost, type 7448.50 and press Enter
4. For the Salvage Value, type 616.25 and press Enter
5. For the Estimated Life, type 6 and press Enter
```===================================================================
Machine Depreciation Evaluation - Straight-Line Method
===================================================================
Enter value to calculate the depreciation of a machine over a certain period of time, using the Straight-Line Method
Machine Cost:   7448.50
Salvage Value:  616.25
Estimated Life: 6
===================================================================
Machine Depreciation Evaluation - Straight-Line Method
===================================================================
Machine Cost:           7448.50
-------------------------------------------------------------------
Salvage Calue:          616.25
-------------------------------------------------------------------
Estimated Life:              6 years
-------------------------------------------------------------------
Yearly Depreciation:    1138.71/year
-------------------------------------------------------------------
Monthly Depreciation:    94.89/month
=====+=====================+============+==========================
Year | Yearly Depreciation | Book Value | Accumulated Depreciation
-----+---------------------+------------+--------------------------
0   |                     |   7448.50  |
-----+---------------------+------------+--------------------------
1   |       1138.71       |   6309.79  |          1138.71
-----+---------------------+------------+--------------------------
2   |       1138.71       |   5171.08  |          2277.42
-----+---------------------+------------+--------------------------
3   |       1138.71       |   4032.38  |          3416.12
-----+---------------------+------------+--------------------------
4   |       1138.71       |   2893.67  |          4554.83
-----+---------------------+------------+--------------------------
5   |       1138.71       |   1754.96  |          5693.54
-----+---------------------+------------+--------------------------
6   |       1138.71       |    616.25  |          6832.25
-----+---------------------+------------+--------------------------```

A List as Parameter

A list is primarily an obect like any other. As a value, a list can be passed as argument. Based on the way Python functions, when setting a parameter for a function, you simply provide a value for the parameter. Here is an example:

```def calculate(values):
pass```

It is when you use the parameter in the body of the function that you can decide to treat it as a list. At that time, the parameter is considered to hold a list and you can then use that parameter any way that is appropriate for a list. Here is an example:

```def display(employee):
i = 0

while i < 9:
print(employee[i])
i = i + 1```

When calling the function, you can pass a list directly in the parentheses of the function. Here is an example:

```def display(employee):
i = 0

while i < 9:
print(employee[i])
i = i + 1

display([ 495826, 'Shannon', 'Ladd', 15.68, 8.5, 9.5, 10, 8, 9.5 ])```

This would produce:

```495826
Shannon
15.68
8.5
9.5
10
8
9.5```

you can also first create a list, store it in a variable, and then pass that variable as argument. Here is an example:

```def display(msg, employee):
i = 0

while i < 9:
print(employee[i])
i = i + 1

employee = [ 495826, 'Shannon', 'Ladd', 15.68, 8.5, 9.5, 10, 8, 9.5 ]

display(employee)```

Just like you can pass a list as argument, you can create a function that takes a combination of parameters, such as a list and a regular value. Here is an example:

```def display(msg, employee):
i = 0

print(msg)

while i < 9:
print(employee[i])
i = i + 1

ttl = "Employee Record"

display(ttl, [ 495826, 'Shannon', 'Ladd', 15.68, 8.5, 9.5, 10, 8, 9.5 ])
print("==================================================")```

Just like a function can use a parameter that is a list, a parameter can use more than one parameter that are a list each. Here is an example:

```def display(msg, identifiers, employee):
i = 0

print(msg)

while i < 9:
print(identifiers[i], ':', employee[i])
i = i + 1

ttl = "Employee Record"
names    = [ "Employee #", "First Name", 'Last Name', "Hourly Salary",
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ]
employee = [ 495826, 'Shannon', 'Ladd', 15.68, 8.5, 9.5, 10, 8, 9.5 ]

display(ttl, names, employee)
print("=========================")```

This would produce:

```Employee Record
Employee # : 495826
First Name : Shannon
Hourly Salary : 15.68
Monday : 8.5
Tuesday : 9.5
Wednesday : 10
Thursday : 8
Friday : 9.5
=========================```

As always, when you are not planning to use a value many times, you don't have to declare a variable for it. Therefore, if you have the lists you want to pass as arguments, you can pass the lists directly to the function. Here is an example:

```def display(msg, identifiers, employee):
i = 0

print(msg)

while i < 9:
print(identifiers[i], ':', employee[i])
i = i + 1

ttl = "Employee Record"

display(ttl, [ "Employee #", "First Name", 'Last Name', "Hourly Salary",
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ],
[ 495826, 'Shannon', 'Ladd', 15.68, 8.5, 9.5, 10, 8, 9.5 ])
print("=========================")```

Lists and Built-In Functions

Introduction

To assist you in creating and managing lists, the Python language ships with a few functions you can use.

The Length of a List

As you may know already, a list is a group of items. Here is an example of some variables:

```number1 = 12.44
number2 = 525.38
number3 = 6.28
number4 = 2448.32
number5 = 632.04```

The items are grouped from a starting to an ending points. They can be created as a list. Here is an example:

`numbers = [ 12.44, 525.38, 6.28, 2448.32, 632.04 ]`

To get the number of items of a list, you can pass the list variable to the built-in len(). Here is an example:

```numbers = [ 12.44, 525.38, 6.28, 2448.32, 632.04 ]

length = len(numbers)

print("The list contains ", length, "numbers.")
print('==================================')```

This would produce:

```The list contains  5 numbers.
==================================
Press any key to continue . . .```

Each item can be located by its index from 0 to the number of items - 1. As opposed to accessing one item at a time, a loop allows you to access the items as a group. Each item can still be accessed by its index. You can first declare a variable that would hold the index for an item. To access an item in a loop, use the variable of the list but pass the index in the square brackets of the variable. Here is an example:

```counter = 0
numbers = [ 12.44, 525.38, 6.28, 2448.32, 632.04 ]

while counter <= 4:
print("Number:", numbers[counter])
counter = counter + 1
print('=================================')```

This would produce:

```Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04
=================================
Press any key to continue . . .```

To change the value of an item, you can access it by its index and assign the desired value to it. Here is an example:

```import random
counter = 0;
numbers = [ 203, 81, 7495, 40, 9580 ]

print("====================================")
print("Original List")
print('-------------')

while counter <= 4:
print("Number: ", numbers[counter])
counter = counter + 1

print('=====================================')
print("Updating the numbers of the list...")

counter = 0;

while counter <= 4:
numbers[counter] = random.randint(1001, 9999);
counter = counter + 1

print("-------------------------------------")

counter = 0

print("Updated Numbers")
print('---------------')

while counter <= 4:
print("Number: ", numbers[counter])
counter = counter + 1
print('=====================================')```

This would produce:

```====================================
Original List
-------------
Number:  203
Number:  81
Number:  7495
Number:  40
Number:  9580
=====================================
Updating the numbers of the list...
-------------------------------------
Updated Numbers
---------------
Number:  9496
Number:  2577
Number:  3351
Number:  7241
Number:  5089
=====================================
Press any key to continue . . .```

Introduction to Ranges of Values

In previous sections, we learned to create lists of random numbers. Sometimes, the values you want to use are in a range from a starting to an ending points. Instead of explicitly creating the values, you can use a function named range (actually, range is a class and what we will call range function here is a constructor of that class). The range() function takes three arguments. One argument is required. If you pass the one required argument, you can provide it as a positive integer. Here is an example:

`range(5)`

If you pass a positive number to the range() function, you get a list of numbers from 0 to that number excluded. If you want, you can assign the range() function to a variable. That variable would hold a list and you can use it as any of the lists we have used so far. Here is an example:

```numbers = range(5)

print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)```

This would produce:

```Number:  0
Number:  1
Number:  2
Number:  3
Number:  4
Press any key to continue . . .```

The range() function can take two arguments as natural numbers. The first argument specifies the starting value of a range of numbers. The second argument represents the end of the range but it is not included in the list. Here is an example:

```numbers = range(4, 12)

print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)```

This would produce:

```Number:  4
Number:  5
Number:  6
Number:  7
Number:  8
Number:  9
Number:  10
Number:  11
Press any key to continue . . .```

When the range() function takes one or two numbers, it creates a list that increases by 1 from one number to the next. The range() function can take three arguments as natural numbers. The first argument specifies the starting value. The second argument represents the end of the range. The third argument specifies the incrementing step from one value to the next. Here is an example:

```numbers = range(5, 35, 3)

print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)
print("Number: ", numbers)```

This would produce:

```Number:  5
Number:  8
Number:  11
Number:  14
Number:  17
Number:  20
Number:  23
Number:  26
Number:  29
Number:  32
Press any key to continue . . .```

Inquiring About a List of Numbers

The Lowest Value

To perform some operations on lists of numbers, you can use some built-in functions. To get the lowest number of a list, call a function named min. Here are examples of calling this function:

```#A list of natural numbers
numbers = [ 29, 35, 4068, 50, 611813 ]
# A list of floating-point numbers
floats  = [ 73.40, 279.85, 6058.06, 55.05 ]

print("Numbers:        ", numbers)
print("Minimum Number: ", min(numbers))
print("-----------------------------------------------")
print("Numbers:        ", floats)
print("Minimum Number: ", min(floats))
print("===============================================")```

This would produce:

```Numbers:         [29, 35, 4068, 50, 611813]
Minimum Number:  29
-----------------------------------------------
Numbers:         [73.4, 279.85, 6058.06, 55.05]
Minimum Number:  55.05
===============================================
Press any key to continue . . .```

The Highest Value

To get the highest value of a list, call a function named max. Here are examples:

```numbers = [ 29, 35, 4068, 50, 611813 ]
floats  = [ 73.40, 279.85, 6058.06, 55.05 ]

print("Numbers:        ", numbers)
print("Minimum Number: ", min(numbers))
print("Maximum Number: ", max(numbers))
print("-----------------------------------------------")
print("Numbers:        ", floats)
print("Minimum Number: ", min(floats))
print("Maximum Number: ", max(floats))
print("===============================================")```

This would produce:

```Numbers:         [29, 35, 4068, 50, 611813]
Minimum Number:  29
Maximum Number:  611813
-----------------------------------------------
Numbers:         [73.4, 279.85, 6058.06, 55.05]
Minimum Number:  55.05
Maximum Number:  6058.06
===============================================
Press any key to continue . . .```

A Sum of Numbers

If you have a list made of numbers, to get the total of those numbers, call a function named sum and pass the list to it. Here are examples:

```numbers = [ 29, 35, 4068, 50, 6183 ]
floats  = [ 73.40, 279.85, 468.06, 155.05 ]

print("Numbers:        ", numbers)
print("Minimum Number: ", min(numbers))
print("Maximum Number: ", max(numbers))
print("Sum of Numbers: ", sum(numbers))
print("-----------------------------------------------")
print("Numbers:        ", floats)
print("Minimum Number: ", min(floats))
print("Maximum Number: ", max(floats))
print("Sum of Numbers: ", sum(floats))
print("===============================================")```

This would produce:

```Numbers:         [29, 35, 4068, 50, 6183]
Minimum Number:  29
Maximum Number:  6183
Sum of Numbers:  10365
-----------------------------------------------
Numbers:         [73.4, 279.85, 468.06, 155.05]
Minimum Number:  73.4
Maximum Number:  468.06
Sum of Numbers:  976.3599999999999
===============================================
Press any key to continue . . .``` Practical Learning: Introducing Loops