- Write loops using
- Write branches using
- Engage in a productive struggle while you write programs without being taught 100% of what you need to know
Control Flow refers to being able to determine what the program does given certain inputs. It controls the flow of the program!
Loops are one type of control flow. Let’s dig in to how they work by taking a look at the program below, focusing on these questions:
- What happens if you continually press c?
- What happens if you press capital C?
- What happens if you press any key other than c?
- What part(s) of the code are repeated when the program runs?
- What part(s) of the code only run once?
- What happens if you remove line 1? Why does this happen?
- What happens if you replace line 1 with
input = "a"? Why?
- What does the
==on line 3 do? What happens if you change it to
Try It: Writing a Loop
Make a new repl (or use this one if you're more comfortable starting with training wheels!). Use what you know about loops and arrays to write a program that collects items on a user's "To-Do" list. Your program should continue asking for more to-dos UNLESS the user presses "e" for exit. Then print out all of the to-do items.
Here's an example of how your program should function:
Add an item to your todo list or press 'e' to exit: unpack suitcase Add an item to your todo list or press 'e' to exit: bring ballot to drop box Add an item to your todo list or press 'e' to exit: finish reading book Add an item to your todo list or press 'e' to exit: e ----------------------------- Here is your todo list: unpack suitcase bring ballot to drop box finish reading book e
NOTE: the "e" for exit will print out in your todo list for now. That's ok! We'll learn how to remove it in the next exercise.
Can you report to the user how many times they've let the loop continue?
Can you report to the user how many times they've pressed a specific letter (for example, "You've pressed 'a' 2 times")?
We’re going to dive right in to reading some code! Before you run the example, guess what the program will do.
Try It: Writing a Loop
Modify your todo program (or use this one if you haven't quite finished your own) to make it so that the letter "e" doesn't get included in your final list.
Can you tell the user how many todos they have on their list each time they are prompted to enter another one? Check out this resource if you need a starting place.
Can you change the interaction pattern of your program so that it will ONLY ask for five todo items and then quit?