while
In Python, the while
keyword defines a loop that executes a block of code as long as a specified condition remains true.
It’s a fundamental tool for performing repeated actions in your programs. The while
loop relies on a condition to control the loop execution. This makes it particularly useful when you don’t know beforehand how many iterations you need.
Python while
Keyword Examples
Here’s an example of how you can use the while
keyword in Python:
>>> count = 0
>>> while count < 5:
... print("Counting:", count)
... count += 1
...
Counting: 0
Counting: 1
Counting: 2
Counting: 3
Counting: 4
In this example, the while
loop executes the block of code that prints the current count and increments it by 1
, as long as count
is less than 5
. Once count
reaches 5
, the condition count < 5
becomes false, and the loop terminates.
Related Resources
Tutorial
Python "while" Loops (Indefinite Iteration)
In this tutorial, you'll learn about indefinite iteration using the Python while loop. You’ll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.
For additional information on related topics, take a look at the following resources:
- How Can You Emulate Do-While Loops in Python? (Tutorial)
- Conditional Statements in Python (Tutorial)
- Python Booleans: Use Truth Values in Your Code (Tutorial)
- Mastering While Loops (Course)
- Python "while" Loops (Quiz)
- Conditional Statements in Python (if/elif/else) (Course)
- Python Conditional Statements (Quiz)
- Python Booleans: Leveraging the Values of Truth (Course)