9.10. Studio: Loops

Now that we've launched our shuttle, let's use loops (iteration) to automate some tasks.

9.10.1. Before You Start

If you are enrolled in a LaunchCode program, access this studio by following the repl.it classroom links posted in your class at learn.launchcode.org.

If you are working through this material on your own, use the repl.it links contained on this page.

9.10.2. Part A (Put dinner together)

  1. First, initialize variables to store the following arrays. Remember to use descriptive names.

    • Protein options:

      ['chicken', 'pork', 'tofu', 'beef', 'fish', 'beans']
      
    • Grain options:

      ['rice', 'pasta', 'corn', 'potato', 'quinoa', 'crackers']
      
    • Vegetable options:

      ['peas', 'green beans', 'kale', 'edamame', 'broccoli', 'asparagus']
      
    • Beverage options:

      ['juice', 'milk', 'water', 'soy milk', 'soda', 'tea']
      
    • Dessert options

      ['apple', 'banana', 'more kale', 'ice cream', 'chocolate', 'kiwi']
      

Code it at replt.it

  1. Use a for loop to assemble 6 meals.
    1. The meals must include one item from each of the source arrays.
    2. Each ingredient can only be used ONCE.
    3. Print out each meal.
  2. Skill boost! (Optional): To enhance your learning, modify your code to:
    1. Use string formatting to print something more interesting than "['chicken', 'rice', 'peas', 'juice', 'apple']" for the meal outputs.
    2. Use an "array of arrays" to store the food options in a 'pantry'.
../../_images/array-of-arrays.png

9.10.3. Part B (Self-destruct system)

If the shuttle gets hijacked by space pirates, the astronauts can activate a self-destruct sequence to provide some drama for the viewers at home.

In order to prevent a rogue astronaut from activating the code, it takes two crew members to begin the countdown. Each person must enter a different code, after which the computer will "zip" them together before overloading the engines.

  1. Construct a for loop that combines two strings together, alternating the characters from each source.

    Examples

    1. If string = "1234" and otherString = "5678", then the output will be "15263748".
    2. If code1 = "ABCDEF" and code2 = "notyet", then the output will be "AnBoCtDyEeFt".
    3. If ka = "LoOt" and blam = "oku!", then the output will be "LookOut!".

    Code it at replt.it

9.10.4. Part C (Refinements)

Update your code from part A to add user input and validation.

  1. Using a while loop, ask the user to select the number of meals to assemble. Validate the input to make sure it is an integer from 1 - 6.

9.10.5. Bonus Mission

Modify your code to check each meal for kale. If present, after the meal output add, "Don't worry, you can have double chocolate tomorrow."