7.3. while loops
Table of Contents
Understanding `while` Loops in Python
A while loop repeats a block of code as long as a condition is True.
The general form is:
while condition:
# code to repeat
# (also called the loop body)- The
conditionis checked before every repetition. - If the condition is
True, the body runs. - When the condition becomes
False, the loop stops.
Basic `while` Loop Example
count = 1
while count <= 5:
print("Count is:", count)
count = count + 1
print("Loop finished!")What happens step-by-step:
- Start:
count = 1 - Check:
count <= 5→1 <= 5→True→ run the body - Print, then update:
countbecomes2 - Check again:
2 <= 5→ stillTrue→ run again
... - When
countbecomes6:6 <= 5→False→ loop ends
Key idea: Something inside the loop must change so that the condition eventually becomes False.
The Importance of Updating the Condition
If you forget to update the variable used in the condition, the loop may never stop.
Example: Infinite Loop (what *not* to do)
number = 1
while number <= 5:
print(number)
# Oops! We forgot: number = number + 1
Here, number is always 1, so number <= 5 is always True.
The loop runs forever (until you manually stop it).
Always check:
- Is my condition correct?
- Am I changing the variables used in the condition inside the loop?
`while` Loops and User Input
while loops are very useful when you don’t know in advance how many times you need to repeat something, especially with user input.
Repeating Until the User Types “quit”
command = ""
while command != "quit":
command = input("Enter a command (or 'quit' to stop): ")
print("You typed:", command)
print("Program ended.")- The loop keeps asking for input until the user types
"quit". - The condition
command != "quit"controls when the loop stops.
Validating User Input
You can use while to keep asking the user until they give a valid answer.
age = int(input("Enter your age (1-120): "))
while age < 1 or age > 120:
print("That doesn't look right.")
age = int(input("Please enter an age between 1 and 120: "))
print("Thanks! Your age is", age)The loop repeats only when the age is outside the allowed range.
Counting Up and Counting Down
while loops often use a counter variable that you increase or decrease each time.
Counting Up
i = 1
while i <= 3:
print("i is", i)
i = i + 1Output:
i is 1
i is 2
i is 3Counting Down
i = 3
while i > 0:
print("i is", i)
i = i - 1
print("Blast off!")Output:
i is 3
i is 2
i is 1
Blast off!Using `while` for Simple Games and Repeated Tasks
Because while loops can run an unknown number of times, they are perfect for:
- Simple guessing games
- Repeating a menu until the user chooses “exit”
- Repeating an action until a certain condition is met
Example: Guessing Until Correct
secret = 7
guess = int(input("Guess the number: "))
while guess != secret:
print("Wrong, try again!")
guess = int(input("Guess the number: "))
print("Correct! The secret number was", secret)
The loop only ends when guess == secret.
`while True` Loops
Sometimes you want a loop that runs “forever” until you manually break out of it from inside.
This is often written as:
while True:
# do something
# maybe break at some pointExample: menu that exits when the user chooses 4:
while True:
print("Menu:")
print("1. Say hello")
print("2. Say goodbye")
print("3. Do nothing")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
elif choice == "3":
print("...")
elif choice == "4":
print("Exiting...")
break # leave the loop
else:
print("Invalid choice. Try again.")Here:
while True:means the loop condition is alwaysTrue.- The only way to leave the loop is with
break.
(The details of break and continue are covered in their own section; here you just see how break can stop a while loop.)
Common `while` Loop Patterns
1. Loop Until a Certain Count
count = 0
while count < 10:
print("Count is", count)
count = count + 12. Loop Until a Condition Becomes False
battery = 100
while battery > 0:
print("Battery at", battery, "%")
battery = battery - 10
print("Battery empty!")3. Loop Until a “Sentinel” Value
A sentinel is a special value that means “stop now”.
total = 0
print("Enter numbers to add. Enter 0 to finish.")
number = int(input("Number: "))
while number != 0:
total = total + number
number = int(input("Number: "))
print("Total is", total)
Here, 0 is the sentinel value that stops the loop.
Typical Mistakes with `while` Loops
1. Forgetting to Update the Variable
x = 0
while x < 5:
print(x)
# missing: x = x + 1 → infinite loop
Always ensure the loop body moves you toward the condition becoming False.
2. Using `==` Instead of `=`
=assigns a value.==compares values.
Inside the loop, you usually want = when you change a variable:
# Wrong:
x == x + 1 # This compares instead of updates
# Right:
x = x + 13. Condition That Is Never True or Never False
- If the condition is never
True, the loop body never runs. - If the condition is never
False, the loop never ends.
Examples:
# Never runs (x starts at 10, but you check for x < 5)
x = 10
while x < 5:
print(x)
x = x + 1
# Never stops (condition always true)
y = 1
while y > 0:
print(y)
y = y + 1When debugging, print the variables used in the condition to see how they change.
When to Use a `while` Loop
Use a while loop when:
- You don’t know in advance how many times you need to repeat something.
- You want to keep going until some condition changes (user input, a value reaches a limit, etc.).
- You’re reacting to something that happens over time (like a menu, a game loop, or repeated checks).
In later sections you will compare while loops to for loops and see when each is more convenient.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!