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 x becomes 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 num becomes 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
  1. Print numbers from 10 to 1 using condition
  2. Keep asking user input until number is positive
  3. Use logical operators inside a while condition
  4. Create a loop that stops when user types exit
Learn Python While Loop with Conditions | Python Course