While Loop with User Input

3 min read ·

While Loop with User Input

What is a while Loop with User Input?

A while loop with user input is used when the number of loop iterations depends on what the user enters.
The loop:
  • Takes input from the user
  • Checks a condition using that input
  • Repeats until the condition becomes False

Basic Example with User Input

  • Loop starts with user input
  • Condition is checked every time
  • New input updates the condition

Loop Runs Until User Enters 0

  • Loop stops when user enters 0

while Loop with String Input

  • Condition checks string value
  • Loop runs until "exit" is entered

Password Validation Using while

  • Loop continues until correct password is entered

Menu-Driven Program Using while

  • Menu keeps showing
  • Loop stops when user selects Exit

while Loop with Boolean and User Input


Common Mistake with User Input Loop

Caution

Loop becomes infinite because input is not updated inside the loop.


Correct Way to Update Input


Using while with Input Validation


while Loop with Multiple User Inputs


Real World Example

Real World Scenario

Application keeps running until user chooses to exit


Exercise

Practice Task
  1. Keep asking numbers until user enters 0
  2. Ask password until correct password is entered
  3. Create a menu using while and user input
  4. Stop loop when user types quit