October 10: While loops

Learning Objectives

After today's class, you should be able to:

  • Trace the execution of loops that change variables.
  • Predict the output of code segments having a loop.
  • Use a loop to build a container of selected results.

Lesson Outline

Inclass Activity

Mini Lecture: More on for loops

Review

Name Create empty Operators Important methods
List [] or list() [i], in, +, * append, count, index, insert, pop, remove
Tuple () or tuple() [i], in, +, * count, index
Set set() only in add, pop, remove
Dict {} or dict() [k], in get, items, pop

Exercise: Short Words

Write a function named get_short(words) that takes a list of words and returns the words that have at most 5 letters. Do not change the list you are given. Instead, follow these steps:

  1. Create an empty list.
  2. Write a for loop that adds one word at a time to the list of short words.
  3. Return the resulting list. (At the end, not in the loop!)

Next step Once this function is tested, create two new functions named get_short_set(words) and get_short_dict(words) these should return the short words in a set or dict respectively. For get_short_dict(words) use the word for the key and the length for the value.

Exercise: Five Stars

Write a function named five_star(hotels) that takes a list of tuples as the input where the first entry in each tuple is the hotel name and the second is the rating. Return a list of hotels that have a rating of 4.5 or higher. For example

>>> five_star([("Ritz",5.0), ("Marriott", 4.5), ("Madison", 4.2)])
["Ritz", "Marriott"]

Once this is tested, create a new function named five_star_dict that takes a dictionary as input. For example, given {"Ritz": 5.0, "Marriott": 4.5, "Madison": 4.2}, return ["Ritz", "Marriott"].

Your To-Do List

Due Wednesday October 11th at 11pm*

  • Submit HW 7 through Canvas and check out the Help page. Remember the attribution statement

Prepare for Quiz 3B

  • Thursday, beginning of class, 25 minutes, in EnGeo 2204.
  • Two parts: concepts and programming (will use lab machine account, canvas and gradescope)
  • Study chapters 5 and 6: both reading and activities
  • Review class activities
  • Review lecture slides from this week regarding for loops

By today

Complete by Monday October 16th

Due Wednesday October 25th at 11pm