Combining Classes and Lists

Introduction

A list is a good way to process a series of object as an entity. A list and other features of the Python language provide various tools and features you can use to deal with a list of objects.

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:
print("================================================================")
print("Machine Depreciation Evaluation - Units of Production")
print("================================================================")

estimated_units : int   = 100_000
machine_cost    : float =  20_000
salvage_value   : float =   5_000
period_type     : str   =  "unit"
nbr_of_years    : int   =      10

years           = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
periods         = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0 ]
depreciations   = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0 ]

# Calculate the periodic depreciation
periodic_depreciation = (machine_cost - salvage_value) / estimated_units

periods[0] =  4_168
periods[1] =  8_820
periods[2] = 10_614
periods[3] = 14_866
periods[4] = 12_304
periods[5] = 21_632
periods[6] = 10_107
periods[7] =  8_434
periods[8] =  5_253
periods[9] =  3_802

depreciations[0] = periods[0] * periodic_depreciation
depreciations[1] = periods[1] * periodic_depreciation
depreciations[2] = periods[2] * periodic_depreciation
depreciations[3] = periods[3] * periodic_depreciation
depreciations[4] = periods[4] * periodic_depreciation
depreciations[5] = periods[5] * periodic_depreciation
depreciations[6] = periods[6] * periodic_depreciation
depreciations[7] = periods[7] * periodic_depreciation
depreciations[8] = periods[8] * periodic_depreciation
depreciations[9] = periods[9] * periodic_depreciation

print(F"Machine Cost:\t\t{machine_cost:6.0f}")
print("----------------------------------------------------------------")
print(F"Salvage Value:\t\t{salvage_value:6.0f}")
print("----------------------------------------------------------------")
print(F"Estimated Units:\t{estimated_units:6.0f} {period_type}s")
print("----------------------------------------------------------------")
print(F"Periodic Depreciation:\t{periodic_depreciation:6.3f}/{period_type}")
print("=====+=====================+==============+=====================")
print("Year | Periodic Operations | Depreciation | Yearly Depreciation")
print("=====+=====================+==============+=====================")
print(F"  1  |\t{periods[0]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[0]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  2  |\t{periods[1]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[1]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  3  |\t{periods[2]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[2]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  4  |\t{periods[3]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[3]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  5  |\t{periods[4]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[4]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  6  |\t{periods[5]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[5]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  7  |\t{periods[6]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[6]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  8  |\t{periods[7]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[7]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  9  |\t{periods[8]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[8]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F" 10  |\t{periods[9]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[9]:8.2f}")
print("-----+---------------------+--------------+---------------------")
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 Exercise20
9. Click Save
10. To execute the application, on the main menu, click Run -> Run Without Debugging
================================================================
Machine Depreciation Evaluation - Units of Production
================================================================
Machine Cost:            20000
----------------------------------------------------------------
Salvage Value:            5000
----------------------------------------------------------------
Estimated Units:        100000 units
----------------------------------------------------------------
Periodic Depreciation:   0.150/unit
=====+=====================+==============+=====================
Year | Periodic Operations | Depreciation | Yearly Depreciation
=====+=====================+==============+=====================
1  |        4168         |     0.150    |       625.20
-----+---------------------+--------------+---------------------
2  |        8820         |     0.150    |      1323.00
-----+---------------------+--------------+---------------------
3  |       10614         |     0.150    |      1592.10
-----+---------------------+--------------+---------------------
4  |       14866         |     0.150    |      2229.90
-----+---------------------+--------------+---------------------
5  |       12304         |     0.150    |      1845.60
-----+---------------------+--------------+---------------------
6  |       21632         |     0.150    |      3244.80
-----+---------------------+--------------+---------------------
7  |       10107         |     0.150    |      1516.05
-----+---------------------+--------------+---------------------
8  |        8434         |     0.150    |      1265.10
-----+---------------------+--------------+---------------------
9  |        5253         |     0.150    |       787.95
-----+---------------------+--------------+---------------------
10  |        3802         |     0.150    |       570.30
-----+---------------------+--------------+---------------------
Press any key to continue . . .

The Type of a List

Because Python is an inferred language, when you create a list, you don't have to specify its type, as long as you at least assign square brackets to the variable. Here is an example:

names :  = []

To support lists, the Python language includes a class named list. You can use this class to perform and maintain some of the operations necessary on lists. For example, if you want to indicate the data type of a list, after the name of variable, type a colon and list. Here is an example:

names : list = []

Practical Learning: Introducing Loops

• Change the document as follows:
print("================================================================")
print("Machine Depreciation Evaluation - Units of Production")
print("================================================================")

estimated_units : int   = 100_000
machine_cost    : float =  20_000
salvage_value   : float =   5_000
period_type     : str   =  "unit"
nbr_of_years    : int   =      10

years         : list = []
periods       : list = []
depreciations : list = []

# Calculate the periodic depreciation
periodic_depreciation = (machine_cost - salvage_value) / estimated_life

. . .

Populating a List

So far, to provide the items of a list, we created a list in the square brackets of a list variable. That approach obliged us to specify in advance the number of items in the list. Sometimes, in the beginning, you don't have the items you want in the list. In this case, you can create an empty list, which is a variable to which you assign empty square brackets, as done in the above two examples. Sometimes, in the beginning, you don't know the number of items the list will have. The list class allows you to add items to a list. To make this possible, the class is equipped with a method named append. When calling it, pass the desired item in the parentheses of the method.

Practical Learning: Introducing Loops

1. Change the document as follows:
estimated_units : int   = 100_000
machine_cost    : float =  20_000
salvage_value   : float =   5_000
period_type     : str   =  "unit"
nbr_of_years    : int   =      10
counter         : int   =       0

years           : list  = []
periods         : list  = []
depreciations   : list  = []

# Calculate the periodic depreciation
periodic_depreciation = (machine_cost - salvage_value) / estimated_units

years.append(counter + 0)
years.append(counter + 1)
years.append(counter + 2)
years.append(counter + 3)
years.append(counter + 4)
years.append(counter + 5)
years.append(counter + 6)
years.append(counter + 7)
years.append(counter + 8)
years.append(counter + 9)

periods.append(4_168)
periods.append(8_820)
periods.append(10_614)
periods.append(14_866)
periods.append(12_304)
periods.append(21_632)
periods.append(10_107)
periods.append(8_434)
periods.append(5_253)
periods.append(3_802)

depreciations.append(periods[0] * periodic_depreciation)
depreciations.append(periods[1] * periodic_depreciation)
depreciations.append(periods[2] * periodic_depreciation)
depreciations.append(periods[3] * periodic_depreciation)
depreciations.append(periods[4] * periodic_depreciation)
depreciations.append(periods[5] * periodic_depreciation)
depreciations.append(periods[6] * periodic_depreciation)
depreciations.append(periods[7] * periodic_depreciation)
depreciations.append(periods[8] * periodic_depreciation)
depreciations.append(periods[9] * periodic_depreciation)

print(F"Machine Cost:\t\t{machine_cost:6.0f}")
print("----------------------------------------------------------------")
print(F"Salvage Value:\t\t{salvage_value:6.0f}")
print("----------------------------------------------------------------")
print(F"Estimated Units:\t{estimated_units:6.0f} {period_type}s")
print("----------------------------------------------------------------")
print(F"Periodic Depreciation:\t{periodic_depreciation:6.3f}/{period_type}")
print("=====+=====================+==============+=====================")
print("Year | Periodic Operations | Depreciation | Yearly Depreciation")
print("=====+=====================+==============+=====================")

counter = 0

print(F"  {years[counter] + 1}  |\t{periods[0]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 0]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 2}  |\t{periods[1]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 1]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 3}  |\t{periods[2]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 2]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 4}  |\t{periods[3]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 3]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 5}  |\t{periods[4]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 4]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 6}  |\t{periods[5]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 5]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 7}  |\t{periods[6]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 6]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 8}  |\t{periods[7]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 7]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F"  {years[counter] + 9}  |\t{periods[8]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 8]:8.2f}")
print("-----+---------------------+--------------+---------------------")
print(F" {years[counter] + 10}  |\t{periods[9]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter + 9]:8.2f}")
print("-----+---------------------+--------------+---------------------")
2. To execute the application, on the main menu, click Run -> Run Without Debugging
3. Change the document as follows:
estimated_units : int   = 100_000
machine_cost    : float =  20_000
salvage_value   : float =   5_000
period_type     : str   =  "unit"
nbr_of_years    : int   =      10
counter         : int   =       0

years           : list  = []
periods         : list  = []
depreciations   : list  = []

# Calculate the periodic depreciation
periodic_depreciation = (machine_cost - salvage_value) / estimated_units

while counter < nbr_of_years:
years.append(counter)
counter = counter + 1

periods.append(4_168)
periods.append(8_820)
periods.append(10_614)
periods.append(14_866)
periods.append(12_304)
periods.append(21_632)
periods.append(10_107)
periods.append(8_434)
periods.append(5_253)
periods.append(3_802)

counter = 0

while counter < nbr_of_years:
depreciations.append(periods[counter] * periodic_depreciation)
counter = counter + 1

print(F"Machine Cost:\t\t{machine_cost:6.0f}")
print("----------------------------------------------------------------")
print(F"Salvage Value:\t\t{salvage_value:6.0f}")
print("----------------------------------------------------------------")
print(F"Estimated Units:\t{estimated_units:6.0f} {period_type}s")
print("----------------------------------------------------------------")
print(F"Periodic Depreciation:\t{periodic_depreciation:6.3f}/{period_type}")
print("=====+=====================+==============+=====================")
print("Year | Periodic Operations | Depreciation | Yearly Depreciation")
print("=====+=====================+==============+=====================")

counter = 0

while counter < nbr_of_years:
print(F"  {years[counter] + 1}  |\t{periods[counter]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter]:8.2f}")
print("-----+---------------------+--------------+---------------------")
counter = counter + 1
4. To execute the application, on the main menu, click Run -> Run Without Debugging
5. Change the document as follows:
print("================================================================")
print("Machine Depreciation Evaluation - Units of Production")
print("================================================================")

estimated_units : int   = 0
machine_cost    : float = 0
salvage_value   : float = 0
period_type     : str   = ""
nbr_of_years    : int   = 1
counter         : int   = 0

years           : list  = []
periods         : list  = []
depreciations   : list  = []

print("Enter the values to calculate the depreciation of a machine over a certain period of time, using the Units of Production method")
machine_cost    = float(input("Machine Cost:    "))
salvage_value   = float(input("Salvage Value:   "))
print("-----------------------------------------")

# We will ask the user to specify the categories of units
# Some machines work by the hour.
# Some machines are considered for the number of items they can produce (nail, screws, etc) or assemble (hammers, batteries, etc)
# Some machines, such as vehicles are considered for the distance upon which they have been used. The distance is considered in kilometers or miles
print("Types of Units")
print("\th - Hours")
print("\tm - Miles")
print("\tu - Units")
print("\to - Other Type")
selection = input( "Specify Unit Type: ")
estimated_units =   int(input("Number of Units:   "))

if (selection == "h") or (selection == "H"):
period_type = "hour"
elif (selection == "m") or (selection == "M"):
period_type = "mile"
elif (selection == "u") or (selection == "U"):
period_type = "unit"
else: #if (selection == "o") or (selection == "O"):
period_type = "other"

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

# Normally, the depreciation is calculated on the basis of the number of years a machine has been used
nbr_of_years    =   int(input("Number of Years:   "))

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

# Here, we create a counter for the years (we could also have used the range() function
while counter < nbr_of_years:
years.append(counter)
counter = counter + 1

counter = 0

# Let the user enter the number of units used for each year
print(F"Enter the number of {period_type}s for each year")

while counter < nbr_of_years:
periods.append(float(input(F"Year {years[counter] + 1}: ")))
counter = counter + 1

# Calculate the periodic depreciation
periodic_depreciation = (machine_cost - salvage_value) / estimated_units

counter = 0

# Create a list of depreciations for each year based on the number of units for that year
while counter < nbr_of_years:
depreciations.append(periods[counter] * periodic_depreciation)
counter = counter + 1

# Display the depreciation report to the user
print("================================================================")
print("Machine Depreciation Evaluation - Units of Production")
print("================================================================")
print(F"Machine Cost:\t\t{machine_cost:6.0f}")
print("----------------------------------------------------------------")
print(F"Salvage Value:\t\t{salvage_value:6.0f}")
print("----------------------------------------------------------------")
print(F"Estimated Units:\t{estimated_units:6.0f} {period_type}s")
print("----------------------------------------------------------------")
print(F"Periodic Depreciation:\t{periodic_depreciation:6.3f}/{period_type}")
print("=====+=====================+==============+=====================")
print("Year | Periodic Operations | Depreciation | Yearly Depreciation")
print("=====+=====================+==============+=====================")

counter = 0

while counter < nbr_of_years:
print(F"  {years[counter] + 1}  |\t{periods[counter]:10.0f}         |\t{periodic_depreciation:6.3f}    |\t{depreciations[counter]:8.2f}")
print("-----+---------------------+--------------+---------------------")
counter = counter + 1
6. To execute, on the main menu, click Run -> Run Without Debugging
7. When requested, enter the values as follows:
 Machine Cost: 16858.75 Salvage Value: 1225.55 Unit Type: h Number of Units: 8800 Number of Years: 6 Year 1: 558 Year 2: 1514 Year 3: 2340 Year 4: 2278 Year 5: 1269 Year 6: 841
================================================================
Machine Depreciation Evaluation - Units of Production
================================================================
Enter the values to calculate the depreciation of a machine over a certain period of time, using the Units of Production method
Machine Cost:    16858.75
Salvage Value:   1225.55
-----------------------------------------
Types of Units
h - Hours
m - Miles
u - Units
o - Other Type
Specify Unit Type: h
Number of Units:   8800
-----------------------------------------
Number of Years:   6
-----------------------------------------
Enter the number of hours for each year
Year 1: 558
Year 2: 1514
Year 3: 2340
Year 4: 2278
Year 5: 1269
Year 6: 841
================================================================
Machine Depreciation Evaluation - Units of Production
================================================================
Machine Cost:            16859
----------------------------------------------------------------
Salvage Value:            1226
----------------------------------------------------------------
Estimated Units:          8800 hours
----------------------------------------------------------------
Periodic Depreciation:   1.777/hour
=====+=====================+==============+=====================
Year | Periodic Operations | Depreciation | Yearly Depreciation
=====+=====================+==============+=====================
1  |         558         |     1.777    |       991.29
-----+---------------------+--------------+---------------------
2  |        1514         |     1.777    |      2689.62
-----+---------------------+--------------+---------------------
3  |        2340         |     1.777    |      4157.01
-----+---------------------+--------------+---------------------
4  |        2278         |     1.777    |      4046.87
-----+---------------------+--------------+---------------------
5  |        1269         |     1.777    |      2254.38
-----+---------------------+--------------+---------------------
6  |         841         |     1.777    |      1494.04
-----+---------------------+--------------+---------------------
Press any key to continue . . .

A List in a Class

A List Variable

To support lists, the Python language includes a class named list. You can use this class to perform and maintain some of the operations necessary on lists.

Practical Learning: Introducing Loops

1. Change the document as follows:



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

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("=========================")

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

The length of a list is the number of items in that list. To get the length of a list, call a function named len. Here is an example:

types_of_cameras = [ "Point of Shoot", 'DSLR', "360" ]
length = len(types_of_cameras)

floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
quantity = len(floats)

print("Types of cameras:", types_of_cameras)
print("Numbers:         ", floats)
print('-------------------------------------------------------')
print("We know", length, "types of cameras.")
print("This list has", quantity, "numbers.")
print("=======================================================")

This would produce:

Types of cameras: ['Point of Shoot', 'DSLR', '360']
Numbers:          [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
-------------------------------------------------------
We know 3 types of cameras.
This list has 6 numbers.
=======================================================
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[0])
print("Number: ", numbers[1])
print("Number: ", numbers[2])
print("Number: ", numbers[3])
print("Number: ", numbers[4])

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[0])
print("Number: ", numbers[1])
print("Number: ", numbers[2])
print("Number: ", numbers[3])
print("Number: ", numbers[4])
print("Number: ", numbers[5])
print("Number: ", numbers[6])
print("Number: ", numbers[7])

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[0])
print("Number: ", numbers[1])
print("Number: ", numbers[2])
print("Number: ", numbers[3])
print("Number: ", numbers[4])
print("Number: ", numbers[5])
print("Number: ", numbers[6])
print("Number: ", numbers[7])
print("Number: ", numbers[8])
print("Number: ", numbers[9])

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