While Loop with Conditions
3 min read ·
A condition in a
while loop is an expression that evaluates to True or False.
The loop keeps running as long as the condition remains True.When the condition becomes False, the loop stops automatically.
Basic while Loop with Condition
- Condition:
i <= 5 - Loop runs while condition is True
- Variable update is required
while Loop with Greater Than Condition
- Condition checks
x > 0 - Loop stops when
xbecomes 0
while Loop with Equality Condition
- Condition is checked every iteration
- Loop runs only while value matches
while Loop with Not Equal Condition
- Loop stops when
numbecomes 5
while Loop with Boolean Condition
- Boolean variable controls the loop
- Commonly used in menus and programs
while Loop with Logical Operators
Using and
- Both conditions must be True
Using or
- Loop runs if any condition is True
Using not
while Loop with User Input Condition
- Loop continues until user enters
0
while Loop with String Condition
Infinite Loop Due to Condition
Caution
Condition never becomes False because i is not updated.
Fixing Infinite Loop with Condition Update
Nested Conditions in while Loop
Real World Example
Real World Scenario
Login system runs until correct password is entered
Exercise
Practice Task
- Print numbers from 10 to 1 using condition
- Keep asking user input until number is positive
- Use logical operators inside a
whilecondition - Create a loop that stops when user types
exit