Python Tutorials · Python While Loops
Python While Loops
Learn all about Python While Loops in this comprehensive tutorial.
5 min read beginner
- •Python has two primitive loop commands:
- •With the while loop we can execute a set of statements as long as a condition is true.
- •With the break statement we can stop the loop even if the while condition is true:
- •With the continue statement we can stop the current iteration, and continue with the next:
- •With the else statement we can run a block of code once when the condition no longer is true:
Python Loops
Python has two primitive loop commands:
- while loops
- for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
python
Note: Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
python
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
python
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
python
Note: Note: The else block will NOT be executed if the loop is stopped by a break statement.
Module quiz
2 questions1
Which of the following is true about Python While Loops?
2
What is the most common pitfall when working with Python While Loops?
Answer all questions to submit.