#********************************************************************** # Counter Loops - February 15, 2019 #********************************************************************** #---------------------------------------------------------------------- # A task to do many times #---------------------------------------------------------------------- def Thing(N): print ("Hello",N) return #---------------------------------------------------------------------- # Version #0 - The hard way to do the task 10 times. Does not scale # well to 20 or 1000 times. #---------------------------------------------------------------------- print ("Version 0") Thing(1) Thing(2) Thing(3) Thing(4) Thing(5) Thing(6) Thing(7) Thing(8) Thing(9) Thing(10) #---------------------------------------------------------------------- # Version #1 - Counter Loop, Counter goes from 1 through 10 #---------------------------------------------------------------------- print ("Version 1") Counter = 1 while (Counter <= 10): Thing(Counter) Counter = Counter + 1 print ("The final value of Counter = ",Counter) #---------------------------------------------------------------------- # Version #2 - Counter Loop, Counter goes from 0 through 9 # This version tends to be more commonly used in Python because # of how it relates to lists and strings. #---------------------------------------------------------------------- print ("Version 2") Counter = 0 while (Counter < 10): Thing(Counter) Counter = Counter + 1 print ("The final value of Counter = ",Counter) #---------------------------------------------------------------------- # Version 3 - Counter Loop, Counter goes 2, 5, 8, 11, 14, 17 # Changing the start value, the stop-test value, and the change value # controls how many times the loop runs and for what values. #---------------------------------------------------------------------- print ("Version 3") Counter = 2 while (Counter < 20): Thing(Counter) Counter = Counter + 3 print ("The final value of Counter = ",Counter) #---------------------------------------------------------------------- # Version 4 - Using a counter loop to step through a list. Notice that # the stop-test value is the length of the list, so the list can # contain any number of items and the counter loop will always run # the correct number of times. #---------------------------------------------------------------------- print ("Version 4") L = [4, 5, 6, 1, 9, 5, 3, 8] Counter = 0 while (Counter < len(L)): print (L[Counter]) Counter = Counter + 1 print ("The final value of Counter = ",Counter)