Counting and Looping
Counting and Looping
Fundamentals of Counting
Introduction
Imagine you have a range of values from a specific starting point to another point and, for any reason, you want to perform an operation on each item in the range. Looping consists of visiting each item of a list. The simplest way to proceed is to work from a preset list of items. Other options use custom lists. You have various options.
Practical Learning: Introducing Loops
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: ")) if estimated_life == 0: print("The value for the length of the estimated life of the machine must always be greater than 0.") yearly_depreciation = (machine_cost - salvage_value) / estimated_life book_value_year0 = machine_cost book_value_year1 = machine_cost - (yearly_depreciation * 1) book_value_year2 = machine_cost - (yearly_depreciation * 2) book_value_year3 = machine_cost - (yearly_depreciation * 3) book_value_year4 = machine_cost - (yearly_depreciation * 4) book_value_year5 = machine_cost - (yearly_depreciation * 5) book_value_year6 = machine_cost - (yearly_depreciation * 6) book_value_year7 = machine_cost - (yearly_depreciation * 7) book_value_year8 = machine_cost - (yearly_depreciation * 8) book_value_year9 = machine_cost - (yearly_depreciation * 9) book_value_year10 = machine_cost - (yearly_depreciation * 10) accumulated_depreciation1 = yearly_depreciation * 1 accumulated_depreciation2 = yearly_depreciation * 2 accumulated_depreciation3 = yearly_depreciation * 3 accumulated_depreciation4 = yearly_depreciation * 4 accumulated_depreciation5 = yearly_depreciation * 5 accumulated_depreciation6 = yearly_depreciation * 6 accumulated_depreciation7 = yearly_depreciation * 7 accumulated_depreciation8 = yearly_depreciation * 8 accumulated_depreciation9 = yearly_depreciation * 9 accumulated_depreciation10 = yearly_depreciation * 10 print("===================================================================") print("Machine Depreciation Evaluation - Straight-Line Method") print("===================================================================") print(F"Machine Cost:\t\t{machine_cost:6.0f}") print("-------------------------------------------------------------------") print(F"Salvage Calue:\t\t{salvage_value:6.0f}") print("-------------------------------------------------------------------") print(F"Estimated Life:\t\t{estimated_life:6.0f} years") print("-------------------------------------------------------------------") print(F"Yearly Depreciation:\t{yearly_depreciation:6.0f}/year") print("-------------------------------------------------------------------") print(F"Monthly Depreciation:\t{(yearly_depreciation / 12):6.0f}/month") print("=====+=====================+============+==========================") print("Year | Yearly Depreciation | Book Value | Accumulated Depreciation") print("-----+---------------------+------------+--------------------------") print(F" 0 |\t\t |{book_value_year0:10.2f} |") print("-----+---------------------+------------+--------------------------") print(F" 1 |\t{yearly_depreciation:12.2f} |{book_value_year1:10.2f} |\t{accumulated_depreciation1:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 2 |\t{yearly_depreciation:12.2f} |{book_value_year2:10.2f} |\t{accumulated_depreciation2:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 3 |\t{yearly_depreciation:12.2f} |{book_value_year3:10.2f} |\t{accumulated_depreciation3:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 4 |\t{yearly_depreciation:12.2f} |{book_value_year4:10.2f} |\t{accumulated_depreciation4:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 5 |\t{yearly_depreciation:12.2f} |{book_value_year5:10.2f} |\t{accumulated_depreciation5:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 6 |\t{yearly_depreciation:12.2f} |{book_value_year6:10.2f} |\t{accumulated_depreciation6:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 7 |\t{yearly_depreciation:12.2f} |{book_value_year7:10.2f} |\t{accumulated_depreciation7:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 8 |\t{yearly_depreciation:12.2f} |{book_value_year8:10.2f} |\t{accumulated_depreciation8:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 9 |\t{yearly_depreciation:12.2f} |{book_value_year9:10.2f} |\t{accumulated_depreciation9:10.2f}") print("-----+---------------------+------------+--------------------------") print(F"10 |\t{yearly_depreciation:12.2f} |{book_value_year10:10.2f} |\t{accumulated_depreciation10:10.2f}")
=================================================================== 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: 22864.75 Salvage Value: 1455.55 Estimated Life: 10 =================================================================== Machine Depreciation Evaluation - Straight-Line Method =================================================================== Machine Cost: 22865 ------------------------------------------------------------------- Salvage Calue: 1456 ------------------------------------------------------------------- Estimated Life: 10 years ------------------------------------------------------------------- Yearly Depreciation: 2141/year ------------------------------------------------------------------- Monthly Depreciation: 178/month =====+=====================+============+========================== Year | Yearly Depreciation | Book Value | Accumulated Depreciation -----+---------------------+------------+-------------------------- 0 | | 22864.75 | -----+---------------------+------------+-------------------------- 1 | 2140.92 | 20723.83 | 2140.92 -----+---------------------+------------+-------------------------- 2 | 2140.92 | 18582.91 | 4281.84 -----+---------------------+------------+-------------------------- 3 | 2140.92 | 16441.99 | 6422.76 -----+---------------------+------------+-------------------------- 4 | 2140.92 | 14301.07 | 8563.68 -----+---------------------+------------+-------------------------- 5 | 2140.92 | 12160.15 | 10704.60 -----+---------------------+------------+-------------------------- 6 | 2140.92 | 10019.23 | 12845.52 -----+---------------------+------------+-------------------------- 7 | 2140.92 | 7878.31 | 14986.44 -----+---------------------+------------+-------------------------- 8 | 2140.92 | 5737.39 | 17127.36 -----+---------------------+------------+-------------------------- 9 | 2140.92 | 3596.47 | 19268.28 -----+---------------------+------------+-------------------------- 10 | 2140.92 | 1455.55 | 21409.20 -----+---------------------+------------+--------------------------
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 book_values[0] = machine_cost - (yearly_depreciation * 1) book_values[1] = machine_cost - (yearly_depreciation * 2) book_values[2] = machine_cost - (yearly_depreciation * 3) book_values[3] = machine_cost - (yearly_depreciation * 4) book_values[4] = machine_cost - (yearly_depreciation * 5) book_values[5] = machine_cost - (yearly_depreciation * 6) book_values[6] = machine_cost - (yearly_depreciation * 7) book_values[7] = machine_cost - (yearly_depreciation * 8) book_values[8] = machine_cost - (yearly_depreciation * 9) book_values[9] = machine_cost - (yearly_depreciation * 10) accumulated_depreciations[0] = yearly_depreciation * 1 accumulated_depreciations[1] = yearly_depreciation * 2 accumulated_depreciations[2] = yearly_depreciation * 3 accumulated_depreciations[3] = yearly_depreciation * 4 accumulated_depreciations[4] = yearly_depreciation * 5 accumulated_depreciations[5] = yearly_depreciation * 6 accumulated_depreciations[6] = yearly_depreciation * 7 accumulated_depreciations[7] = yearly_depreciation * 8 accumulated_depreciations[8] = yearly_depreciation * 9 accumulated_depreciations[9] = yearly_depreciation * 10 print("===================================================================") print("Machine Depreciation Evaluation - Straight-Line Method") print("===================================================================") print(F"Machine Cost:\t\t{machine_cost:6.0f}") print("-------------------------------------------------------------------") print(F"Salvage Calue:\t\t{salvage_value:6.0f}") print("-------------------------------------------------------------------") print(F"Estimated Life:\t\t{estimated_life:6.0f} years") print("-------------------------------------------------------------------") print(F"Yearly Depreciation:\t{yearly_depreciation:6.0f}/year") print("-------------------------------------------------------------------") print(F"Monthly Depreciation:\t{(yearly_depreciation / 12):6.0f}/month") print("=====+=====================+============+==========================") print("Year | Yearly Depreciation | Book Value | Accumulated Depreciation") print("-----+---------------------+------------+--------------------------") print(F" 0 |\t\t |{book_value_year0:10.2f} |") print("-----+---------------------+------------+--------------------------") print(F" 1 |\t{yearly_depreciation:12.2f} |{book_values[0]:10.2f} |\t{accumulated_depreciations[0]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 2 |\t{yearly_depreciation:12.2f} |{book_values[1]:10.2f} |\t{accumulated_depreciations[1]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 3 |\t{yearly_depreciation:12.2f} |{book_values[2]:10.2f} |\t{accumulated_depreciations[2]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 4 |\t{yearly_depreciation:12.2f} |{book_values[3]:10.2f} |\t{accumulated_depreciations[3]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 5 |\t{yearly_depreciation:12.2f} |{book_values[4]:10.2f} |\t{accumulated_depreciations[4]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 6 |\t{yearly_depreciation:12.2f} |{book_values[5]:10.2f} |\t{accumulated_depreciations[5]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 7 |\t{yearly_depreciation:12.2f} |{book_values[6]:10.2f} |\t{accumulated_depreciations[6]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 8 |\t{yearly_depreciation:12.2f} |{book_values[7]:10.2f} |\t{accumulated_depreciations[7]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F" 9 |\t{yearly_depreciation:12.2f} |{book_values[8]:10.2f} |\t{accumulated_depreciations[8]:10.2f}") print("-----+---------------------+------------+--------------------------") print(F"10 |\t{yearly_depreciation:12.2f} |{book_values[9]:10.2f} |\t{accumulated_depreciations[9]:10.2f}")
=================================================================== 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: 14555.95 Salvage Value: 885.75 Estimated Life: 10 =================================================================== Machine Depreciation Evaluation - Straight-Line Method =================================================================== Machine Cost: 14556 ------------------------------------------------------------------- Salvage Calue: 886 ------------------------------------------------------------------- Estimated Life: 10 years ------------------------------------------------------------------- Yearly Depreciation: 1367/year ------------------------------------------------------------------- Monthly Depreciation: 114/month =====+=====================+============+========================== Year | Yearly Depreciation | Book Value | Accumulated Depreciation -----+---------------------+------------+-------------------------- 0 | | 14555.95 | -----+---------------------+------------+-------------------------- 1 | 1367.02 | 13188.93 | 1367.02 -----+---------------------+------------+-------------------------- 2 | 1367.02 | 11821.91 | 2734.04 -----+---------------------+------------+-------------------------- 3 | 1367.02 | 10454.89 | 4101.06 -----+---------------------+------------+-------------------------- 4 | 1367.02 | 9087.87 | 5468.08 -----+---------------------+------------+-------------------------- 5 | 1367.02 | 7720.85 | 6835.10 -----+---------------------+------------+-------------------------- 6 | 1367.02 | 6353.83 | 8202.12 -----+---------------------+------------+-------------------------- 7 | 1367.02 | 4986.81 | 9569.14 -----+---------------------+------------+-------------------------- 8 | 1367.02 | 3619.79 | 10936.16 -----+---------------------+------------+-------------------------- 9 | 1367.02 | 2252.77 | 12303.18 -----+---------------------+------------+-------------------------- 10 | 1367.02 | 885.75 | 13670.20
The primary way to visit each number of a range uses a keyword named while. The formula to follow is:
while condition: statement(s)
The while loop can be illustrated as follows:
Start with the while keyword and a semicolon. Between the while keyword and the semicolon, create a logical expression and a condition that can produce a True or a False value. After the colon, go to next line, indent it and write the statement(s) to be executed. The line(s) after the colon is/are called the body of the while counter.
Normally, the while operator is used to visit numbers in a range from one starting point to a finishing point. The while operator is not equipped to set the starting point. That starting point is usually set before starting with the while operation. This can be done by declaring a variable and initializing it with the desired starting value.
In the body of the while counter, create one or more statements to execute every time the condition is true. You should (must) also provide a way to move from one value to the next (or the previous). This is usually done by increasing (or decreasing) the value of the starting value. Here is an example:
number = 1 # Loop start while number <= 5: # As long as the above value is lower than 5, ... # ... display that number print(number, " - Make sure you review the time sheet before submitting it.") # Increase the number (or counter) number = number + 1 print('==============================================================')
This would produce:
1 - Make sure you review the time sheet before submitting it. 2 - Make sure you review the time sheet before submitting it. 3 - Make sure you review the time sheet before submitting it. 4 - Make sure you review the time sheet before submitting it. 5 - Make sure you review the time sheet before submitting it. ============================================================== Press any key to continue . . .
The while loop is used to first check a condition and then execute a statement. If the condition is false, the statement would never execute. Consider the following code:
number = 5 # Loop while number <= 4: print("Make sure you review the time sheet before submitting it.") number = number + 1
When this code executes, nothing from the while loop would execute because, as the condition is checked in the beginning, it is false and the compiler would not get to the statement.
While Visiting a List
Based on this ability to visit each member of a range, if you have a list of items, you can use a while loop to visit some items in the list and perform the desired operation.
Practical Learning: Introducing Loops
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: ")) if estimated_life == 0: print("The value for the length of the estimated life of the machine must always be greater than 0.") yearly_depreciation = (machine_cost - salvage_value) / estimated_life book_values_year0 = machine_cost i : int = 0 while i <= 10: 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.0f}/year") print("-------------------------------------------------------------------") print(F"Monthly Depreciation:\t{(yearly_depreciation / 12):6.0f}/month") print("=====+=====================+============+==========================") print("Year | Yearly Depreciation | Book Value | Accumulated Depreciation") print("-----+---------------------+------------+--------------------------") print(F" 0 |\t\t |{book_value_year0:10.2f} |") print("-----+---------------------+------------+--------------------------") while i < 10: print(F" {i + 1} |\t{yearly_depreciation:12.2f} |{book_values[i]:10.2f} |\t{accumulated_depreciations[i]:10.2f}") print("-----+---------------------+------------+--------------------------") i = i + 1
=================================================================== 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: 17836.75 Salvage Value: 1225.85 Estimated Life: 10 =================================================================== Machine Depreciation Evaluation - Straight-Line Method =================================================================== Machine Cost: 17836.75 ------------------------------------------------------------------- Salvage Calue: 1225.85 ------------------------------------------------------------------- Estimated Life: 10 years ------------------------------------------------------------------- Yearly Depreciation: 1661/year ------------------------------------------------------------------- Monthly Depreciation: 138/month =====+=====================+============+========================== Year | Yearly Depreciation | Book Value | Accumulated Depreciation -----+---------------------+------------+-------------------------- 0 | | 17836.75 | -----+---------------------+------------+-------------------------- 1 | 1661.09 | 16175.66 | 1661.09 -----+---------------------+------------+-------------------------- 2 | 1661.09 | 14514.57 | 3322.18 -----+---------------------+------------+-------------------------- 3 | 1661.09 | 12853.48 | 4983.27 -----+---------------------+------------+-------------------------- 4 | 1661.09 | 11192.39 | 6644.36 -----+---------------------+------------+-------------------------- 5 | 1661.09 | 9531.30 | 8305.45 -----+---------------------+------------+-------------------------- 6 | 1661.09 | 7870.21 | 9966.54 -----+---------------------+------------+-------------------------- 7 | 1661.09 | 6209.12 | 11627.63 -----+---------------------+------------+-------------------------- 8 | 1661.09 | 4548.03 | 13288.72 -----+---------------------+------------+-------------------------- 9 | 1661.09 | 2886.94 | 14949.81 -----+---------------------+------------+-------------------------- 10 | 1661.09 | 1225.85 | 16610.90 -----+---------------------+------------+--------------------------
=================================================================== 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: 6425.65 Salvage Value: 855.75 Estimated Life: 5 =================================================================== Machine Depreciation Evaluation - Straight-Line Method =================================================================== Machine Cost: 6425.65 ------------------------------------------------------------------- Salvage Calue: 855.75 ------------------------------------------------------------------- Estimated Life: 5 years ------------------------------------------------------------------- Yearly Depreciation: 1114/year ------------------------------------------------------------------- Monthly Depreciation: 93/month =====+=====================+============+========================== Year | Yearly Depreciation | Book Value | Accumulated Depreciation -----+---------------------+------------+-------------------------- 0 | | 6425.65 | -----+---------------------+------------+-------------------------- 1 | 1113.98 | 5311.67 | 1113.98 -----+---------------------+------------+-------------------------- 2 | 1113.98 | 4197.69 | 2227.96 -----+---------------------+------------+-------------------------- 3 | 1113.98 | 3083.71 | 3341.94 -----+---------------------+------------+-------------------------- 4 | 1113.98 | 1969.73 | 4455.92 -----+---------------------+------------+-------------------------- 5 | 1113.98 | 855.75 | 5569.90 -----+---------------------+------------+-------------------------- 6 | 1113.98 | -258.23 | 6683.88 -----+---------------------+------------+-------------------------- 7 | 1113.98 | -1372.21 | 7797.86 -----+---------------------+------------+-------------------------- 8 | 1113.98 | -2486.19 | 8911.84 -----+---------------------+------------+-------------------------- 9 | 1113.98 | -3600.17 | 10025.82 -----+---------------------+------------+-------------------------- 10 | 1113.98 | -4714.15 | 11139.80 -----+---------------------+------------+--------------------------
Managing a Loop
Loops and Conditional Statements
In the body of a loop, you can create a conditional statement to check whatever condition you want and take an appropriate action.
Practical Learning: Introducing Loops
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: "))
if estimated_life == 0:
print("The value for the length of the estimated life of the machine must always be greater than 0.")
yearly_depreciation = (machine_cost - salvage_value) / estimated_life
book_value_year0 = machine_cost
i : int = 0
while i <= 10:
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 < 10:
if book_values[i] > 0:
print(F" {i + 1} |\t{yearly_depreciation:12.2f} |{book_values[i]:10.2f} |\t{accumulated_depreciations[i]:10.2f}")
print("-----+---------------------+------------+--------------------------")
i = i + 1
=================================================================== 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: 6425.85 Salvage Value: 855.75 Estimated Life: 5 =================================================================== Machine Depreciation Evaluation - Straight-Line Method =================================================================== Machine Cost: 6425.85 ------------------------------------------------------------------- Salvage Calue: 855.75 ------------------------------------------------------------------- Estimated Life: 5 years ------------------------------------------------------------------- Yearly Depreciation: 1114/year ------------------------------------------------------------------- Monthly Depreciation: 93/month =====+=====================+============+========================== Year | Yearly Depreciation | Book Value | Accumulated Depreciation -----+---------------------+------------+-------------------------- 0 | | 6425.85 | -----+---------------------+------------+-------------------------- 1 | 1114.02 | 5311.83 | 1114.02 -----+---------------------+------------+-------------------------- 2 | 1114.02 | 4197.81 | 2228.04 -----+---------------------+------------+-------------------------- 3 | 1114.02 | 3083.79 | 3342.06 -----+---------------------+------------+-------------------------- 4 | 1114.02 | 1969.77 | 4456.08 -----+---------------------+------------+-------------------------- 5 | 1114.02 | 855.75 | 5570.10 -----+---------------------+------------+--------------------------
Locating an Item in a Loop
If you want to find an item in a list, you can nest a conditional statement (if, etc) in a while counter or a for loop. Once you have located the desired item, you can take appropriate action. Here is an example:
counter = 0
item_to_look_for = "DSLR"
types_of_cameras = [ "Point of Shoot", 'DSLR', "360" ]
print("Types of cameras:", types_of_cameras)
print("----------------------------------------------")
while counter <= 2:
if types_of_cameras[counter] == item_to_look_for:
print("Camera Found: ", types_of_cameras[counter])
counter = counter + 1
print("==============================================")
This would produce:
Types of cameras: ['Point of Shoot', 'DSLR', '360'] ---------------------------------------------- Camera Found: DSLR ============================================== Press any key to continue . . .
As mentioned in our introductions, a loop is supposed to navigate from a starting point to an ending value. Sometimes, for any reason, you want to stop that navigation before the end of the loop. To do this, use a keyword named break. The formula to use the break statement is:
break
Although made of only one word, the break statement is a complete statement; therefore, it can (and should always) stay on its own line (this makes the program easy to read).
The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable. The break statement can be used in a while condition or a for loop to stop an ongoing operation. Here is an example that is used to count the levels of a house from 1 to 12 but it is asked to stop at 3:
number = 0
while number <= 5:
print("The time sheet was checked and this payroll has been approved.")
if number == 2:
break
number = number + 1
print("===============================================================")
This would produce:
The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. =============================================================== Press any key to continue . . .
Continuing a Conditional Statement
Instead of stopping the flow of a loop, you may want to skip one of the values. To do this, use a keyword named continue keyword. The formula to use it is:
continue
When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement, it must stay on its own line and must be indented. Here is an example that is supposed to count the levels of a house from 1 to 6:
strNumbers = ""
number = 0
while number <= 5:
strNumbers = strNumbers + str(number) + " "
print("The list of numbers is ", strNumbers)
number = number + 1
if number == 3:
continue
print("===========================================")
This would produce:
The list of numbers is 0 The list of numbers is 0 1 The list of numbers is 0 1 2 The list of numbers is 0 1 2 4 The list of numbers is 0 1 2 4 5 =========================================== Press any key to continue . . .
Notice that, when the compiler gets to 3, it ignores it.
Changing a Value in the Loop
Inside a loop, you may want to put a flag that would monitor the evolution of a piece of code so that, if a certain value is encountered, instead of skipping the looping by 1, you can make it jump to a valued range of your choice. To do this, in the loop, check the current value and if it gets to one you are looking for, change it. Here is an example where a loop is asked to count from 0 to 15:
number = 0
strNumbers = ""
while number <= 15:
strNumbers = strNumbers + str(number) + " "
number = number + 1
if number == 6:
number = 10
print("The list of numbers is ", strNumbers)
print("======================================================")
This would produce:
The list of numbers is 0 1 2 3 4 5 10 11 12 13 14 =================================================== Press any key to continue . . .
Notice that, when the loop reaches 6, it is asked to jump to number 10 instead.
while True
For the different situations in which we used a while condition so far, we included a means of checking the condition. As an option, you can include just the True Boolean constant in the parentheses of True. Here is an example:
while True:
print("Application development is fun!!!")
This type of statement is legal and would work fine, but it has no way to stop because it is telling the compiler "As long as 'this' is true, ...". The question is, what is "this"? As a result, the program would run forever. Therefore, if you create a while True condition, in the body of the statement, you should (must) provide a way for the compiler to stop, that is, a way for the condition to be (or to become) False. This can be done by including an if conditional statement. Here is an example:
i = 0 while True: if i > 8: break print("Application development is fun!!!") i = i + 1 print("=================================")
This would produce:
Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! Application development is fun!!! ================================= Press any key to continue . . .
Instead of using while True, you can first declare and initialize a Boolean variable, or you can use a Boolean variable whose value is already known. The value can come from a function or by other means.
For Each Item in a List
Loops are mostly used to help to manage a list of items. This is done by accessing or visiting each item, and then taking action on the accessed item. Besides the while keyword, the primary operator used to access each member of a list is named for. The primary formula to use it is:
for variable in list: statement;
The loop starts with the for keyword followed by a (letter or a name for a) variable. This is followed by an operator named in. You can then add a list that is followed by a colon. After this list, the next section contains the code that should execute. That section is the body of the loop. It must be indented. In that body, at a minimum, you can pass the variable to a print() function. Here is an example:
for nbr in [ 203, 81, 7495, 40, 9580 ]: print("Number: ", nbr) print('=====================================')
This would produce:
Number: 203 Number: 81 Number: 7495 Number: 40 Number: 9580 ===================================== Press any key to continue . . .
If you have a variable that holds a list, you can provide that variable in place of the list in our formula. Here is an example:
provinces = [ 'Saskatchewan', "British Columbia", 'Ontario', "Alberta", 'Manitoba' ] # Using a "for" for administration in provinces: print("Province:", administration) print('=====================================')
This would produce:
Province: Saskatchewan Province: British Columbia Province: Ontario Province: Alberta Province: Manitoba ===================================== Press any key to continue . . .
Nesting a Conditional Statement
Consider the following list:
numbers = [ 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 ]
Imagine you want to access only the first n members of the list. To do this, you can use an if conditional statement nested in a for loop. Here is an example that produces the first 4 values of the list:
i = 0 numbers = [ 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 ] for nbr in numbers: if i < 4: print("Number: ", nbr) i = i + 1 print("=================================")
This would produce:
Number: 102 Number: 44 Number: 525 Number: 38 =============================== Press any key to continue . . .
You can use the same technique to get the last m members of a list. You can also use a similar technique to get one or a few values inside of the list, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the list:
i = 0 numbers = [ 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 ] for nbr in numbers: if nbr % 5 == 0: print("Number: ", nbr) i = i + 1 print("=================================")
This would produce:
Number: 525 =============================== Press any key to continue . . .
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2021-2022, FunctionX | Friday 31 December 2021 | Next |
|