- Define "repetition" as a core programming concept.
- Use the
whilekeyword to create a loop that repeats as long as a condition is true. - Understand the importance of an "exit condition" to prevent infinite loops.
The Power of Repetition
Computers are incredibly fast, but their real superpower is their ability to perform the same task millions of times without getting bored or making mistakes. This is called repetition or "looping." The first type of loop we will learn is the while loop.
The while Loop
A while loop is like an if statement that keeps repeating. It checks a condition, and as long as that condition is True, it will execute a block of indented code over and over again. As soon as the condition becomes False, the loop stops, and the program continues on.
while some_condition_is_true:
This indented block of code will repeat
as long as the condition above is True.
do_this_action() do_this_again()
For a while loop to stop, something inside the loop must eventually make the condition False. If the condition never becomes false, you have created an infinite loop! Your program will get stuck and run forever. If this happens, you can usually click the "Stop" button in your IDE to end it.
Live Example: The Countdown
The code below shows a simple counter-controlled loop. A variable count is initialized to 5. The loop continues as long as count is greater than 0. Crucially, inside the loop, we subtract 1 from count each time. This ensures that the condition will eventually become false and the loop will end.
Your challenge: Run the code. Then, try changing the starting value of count to 10. What happens if you comment out the line count = count - 1? (Hint: You'll see an infinite loop!)
A while loop is perfect for situations where you don't know how many times the loop needs to run. You just know that it needs to continue while some condition is true. This is exactly the tool we will need for our "Guess the Number" game project!
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.