The need to have programs perform the same task multiple times over is common, and it would be tedious to copy and paste the same code for as many times as you need to run it. That’s where repetition structures come in.


The while loop The while loop is a condition-controlled loop. A condition controlled loop causes a statement, or set of statements to repeat as long as the condition is true.
        1 
        2 while condition_true:
        3    statement runs
        4    
        
        1 number = 5
        2 while number <= 5:
        3    print("Your number is", number)
        4    number = int(input("Input another number: "))
        
Since this is a prestest loop, it first tests the condition before the loop is run. In the example, it has to test whether or not the variable number exists, and then determine whether the condition is true. Just be careful of infinite loops



The for loop The for loop is a count-controlled loop. You'll choose to use this type of loop when you have to do something a specific amount of times.
        1 
        2 for variable in [value1, value2, value3]:
        3    statement runs through
        4    each value one by one
        
        1 print('This program will display each number.')
        2 for num in [35, 66, 12, 1, 7, 0]:
        3    print(num)
        4    
        
The for clause assigns a variable that will take on the value depending on the statement we give it within the loop. First, num is assigned to the number 35, then on the second loop it is assigned to number 66 and so on until it executes each iteration of the list of numbers in the loop. The range method is an option to use with a for clause if you'd like to be specicic about your iterations.

You can pass it a single argument:
        1 
        2 for num in range(5):
        3    print(num)
        4    
        

This will print out 1 through 5.

Two arguments:
        1 
        2 for num in range(1, 5):
        3    print(num)
        4    
        

In this case, it'll print out numbers 1-4 since we're telling it to start at 1 and go up-to but not including 5.

Or three arguments:
        1 
        2 for num in range(1, 10, 2):
        3    print(num)
        4    
        

The first argument is 1, so we'll start at 1. The second argument is 10, so we'll go up to but not include 10. The third argument is 2 which is the step value. This means that the number 2 will be added to each successive number in the sequence.

It will print out the numbers 1, 3, 5, 7, 9.



Using an accumulator Calculating a running total to show how an accumulator works. Introducing: Augmented Assignment Operators! We've seen variables on the left, and values on the right, like so:
x = 10
But when we need to increment a variable, we have to put that variable on the right side of the equation as well:
x = x + 10
When we incorperate this into a loop, each iteration of the loop increments the value of x by 10.
        1 total = 0
        2 for count in range(1, 6):
        3    total = total + count
        4 print(total) 
        
This code will continue to add the numbers 1-5 to total, which is set to 0 initially and eventually print out the single number 15.



Input validation loops A quick ditty on catching "bad" data before it enters the program. This will allow us to display an error message to the user if the program recieves incorrect or bad data.
        1 hours = int(input('Enter the hours worked this week: '))
        2 rate = float(input('Enter the hourly pay rate: '))
        3 gross_pay = hours * pay_rate
        4  print('Gross pay: $', format(gross_pay, ',.2f'))
        
Here we're not checking to make sure the user doesn't enter an unreasonable number of hours worked per week, 400, for example. Since there are only 168 hours in a week, 400 hours worked in a week would be "bad" data.
        1 hours = int(input('Enter the hours worked this week: '))
        2 if hours > 168:
        3   print("You've entered too many hours!")
        4 elif hours < 168:
        5   rate = float(input('Enter the hourly pay rate: '))
        6   if rate > 1000000:
        7       print("You paid them too much!")
        8   elif rate < 1000000:
        9       gross_pay = hours * pay_rate
        10 print('Gross pay: $', format(gross_pay, ',.2f'))
        




Nested loops You can put loops inside of loops inside of loops inside of loops... Let's build a clock to showcase this one:
        1 for hours in range(60):
        2   
        3   for minutes in range(60):
        4       
        5       for seconds in range(60):
        6           print(hours, ':' ,minutes, ':' ,seconds )
        
Run that code to see how it operates! First, the inner loop goes through all of its iterations. That's why we see the seconds variable counting up to 60 first. Then minutes runs through, and then hours.


Happy coding!

E


Got Questions❓, Comments 🗣 or Edits ✍

Use the Twitter thread below and hashtag #E4Everything to get in touch with me regarding this blog post:

Previous: OAuth with ReactJSNext: Functions