While Loop
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
While Loop
Definition: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop continues to run as long as the condition remains True.
Why: While loops are essential when you don't know in advance how many times a block of code needs to run, but you do know the condition that should stop it (e.g., waiting for a specific user input or reaching a mathematical threshold).
Syntax
while condition:
# code to execute
# update condition
Example
i = 1
while i <= 5:
print(i)
i += 1
Explanation
- Initial Variable: We start with
i = 1. - Condition: The loop checks if
i <= 5. Since 1 is less than 5, the code inside runs. - Execution: The current value of
iis printed. - Update:
i += 1increases the value ofi. If we didn't do this, the loop would run forever (an infinite loop). - Termination: Once
ibecomes 6, the condition6 <= 5becomesFalse, and the loop stops.
Key Notes
- Indentation: Just like
ifstatements, the code inside thewhileloop must be indented. - Infinite Loops: Always ensure the condition will eventually become
False. If the loop never stops, it can crash your program. - Breaking a Loop: You can use the
breakstatement to stop a loop immediately, even if the condition is still true.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute