While Loops for Tracking Steps
Explore how to use while loops to repeatedly gather step counts and sum them until the user chooses to stop. This lesson guides you through creating an interactive web-based step tracker with input fields and buttons, teaching you to manage user input, update totals dynamically, and avoid common programming pitfalls like infinite loops and invalid input.
The project
Let’s say you’ve decided to track your daily steps. Entering your steps once and stopping gives you only a snapshot, but it doesn’t help track progress over time. A smartwatch solves this by continually collecting your daily totals until you decide to stop.
Printing a single number like Steps today: 1,000 can be useful, but it doesn’t show the full picture. What you really need is a system that keeps collecting your input until you’re done, and then reports the total steps you have taken so far. In programming, we build this kind of behavior with a loop.
Your project: build a daily step tracker that collects steps entry by entry, adds them up, and stops only when the user chooses.
The programming concept
Imagine you’re a cashier. Customers keep coming up and asking, “How much does this cost?” You don’t just answer once; you keep answering until the store closes. That’s how a while loop works: it keeps running if a condition is true. Let’s look at a while loop in action. Read the code before clicking “Run,” and think about what ...