Loops: while and do-while loops
Following our exploration of Loops: for loops (Part 2), this article introduces another type of loop: the while loop. We'll also see how to simulate a do-while loop, which is not a native feature of Python.
📚 Prerequisites
A basic understanding of Python loops and conditional statements.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ The syntax of the
whileloop. - ✅ How to use
whileloops to repeat code based on a condition. - ✅ How to create infinite loops and how to break out of them.
- ✅ How to simulate a
do-whileloop in Python.
🧠 Section 1: The while Loop
The while loop repeatedly executes a block of code as long as a given condition is True.
Syntax:
while condition:
# code to be executed
condition: A boolean expression that is evaluated before each iteration.
Example:
count = 0
while count < 5:
print(count)
count += 1
In this example, the loop will continue as long as count is less than 5. It's crucial to have a way to make the condition False at some point, otherwise you'll have an infinite loop.
💻 Section 2: Infinite Loops and break
An infinite loop is a loop that runs forever because its condition always remains True. You can use the break statement to exit a loop at any time.
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print(f"You entered: {user_input}")
🛠️ Section 3: Simulating a do-while Loop
Python doesn't have a built-in do-while loop. A do-while loop is a loop that executes the code block at least once, and then checks the condition at the end of the loop.
You can simulate a do-while loop using a while True loop with a break statement at the end:
while True:
# code to be executed at least once
user_input = input("Enter a number: ")
number = int(user_input)
print(f"The square of your number is {number ** 2}")
# check the condition at the end
if number < 0:
break
💡 Conclusion & Key Takeaways
You've now learned how to use while loops to create more flexible and powerful programs.
Let's summarize the key takeaways:
whileLoop: Repeats a block of code as long as a condition isTrue.- Infinite Loops: Can be created with
while Trueand exited withbreak. do-whileLoop: Not a native feature of Python, but can be simulated withwhile Trueandbreak.
Challenge Yourself: Write a script that simulates a simple guessing game. The script should generate a random number between 1 and 10, and then ask the user to guess the number. The script should continue to ask for guesses until the user guesses the correct number.
➡️ Next Steps
In the next article, we'll learn about "Loops: foreach loops".
Happy coding!
Glossary (Python Terms)
whileloop: A control flow statement that allows code to be executed repeatedly based on a given boolean condition.- Infinite loop: A loop that continues to execute forever.
do-whileloop: A loop that executes a block of code at least once, and then repeatedly executes the block as long as a condition is true.