Python 101

Week 4:
Loops

Expedia Code Academy

For loops

For loops are a way to loop (or "iterate") through a list.

            expedia_brands = ['Hotels.com', 'EPS', 'Expedia'] 
            
            for brand in expedia_brands:
                print('I love ' + brand)

            for scoobydoo in expedia_brands:  # same as the above for loop
                print('I love ' + scoobydoo)
          

The word variable is recreated every round of the loop, with the value of the next item in the list.

You can name it anything you like! Just use the same variable name within the for loop.

Strings can be treated like lists

What do we think this code will do?


              my_string = 'Today is a great day!'
              print(my_string[0])
            

Strings are simply lists of characters!


                total = 0
                my_string = 'Today is a great day!'
                
                for letter in my_string:
                    ??? 
              
(⭐️) 4c. Count the number of 'a's in my_string.

While or for loops?

While loops are useful when you want something to loop forever, or until something changes!

For loops are useful when you have your data already and want to loop through it until it ends.

What about these examples?

  • You want to ask for user input() until they type the string 'EXIT'.
  • You have a list of exam marks, and want to see how many are above a pass mark.
  • You want to process a list of numbers until you encounter a negative number

Exercises


            some_numbers = [1.5, 37.2, 55, -1.94]
          
  • (⭐) 4d. Using some_numbers, print each element multiplied by 10.
    Example output: 15.0, 372.0, 550, -19.4

  • (⭐⭐) 4e. Count how many words in a given list are longer than 3 letters. See here for a list of words to use.