Nearby lessons

42 of 159

Python - While Loop

📌 What You Will Learn
  • Define the while loop and when it is used
  • Explain the flow of a while loop that checks the condition before each iteration
  • Write while loops to print numbers, even numbers, odd numbers and reverse counting
  • Identify why an infinite loop occurs when the loop variable is not updated
  • Apply the while loop when the number of iterations is not known

What is a while Loop?

The while loop executes a group of statements as long as the given condition is True.

When the condition becomes False, the loop stops.

Syntax of while Loop

Loading editor…

Flow of while Loop

  1. Check the condition.
  2. If the condition is True, execute the loop body.
  3. Again check the condition.
  4. Repeat until the condition becomes False.
  5. When the condition becomes False, control comes outside the loop.

Example 1 - Print "Hello" 10 Times

Loading editor…

Explanation

The variable i starts from 1.

After every iteration, its value increases by 1.

The loop stops when i becomes greater than 10.

Example 2 - Print Numbers from 1 to 10

Loading editor…

Example 3 - Print Numbers from 1 to 20

Loading editor…

Example 4 - Print Even Numbers from 1 to 20

Loading editor…

Explanation

The loop starts from 2.

Each time, the value increases by 2, so only even numbers are printed.

Example 5 - Print Odd Numbers from 1 to 20

Loading editor…

Explanation

The loop starts from 1.

Each time, the value increases by 2, so only odd numbers are printed.

Example 6 - Print Numbers from 10 to 1

Loading editor…

Explanation

The loop starts from 10.

After every iteration, the value decreases by 1.

The loop stops when the value becomes less than 1.

Infinite while Loop

If the condition is always True, the loop runs forever.

Such a loop is called an Infinite Loop.

Example - Infinite while Loop

Loading editor…

Why Does an Infinite Loop Occur?

An infinite loop happens when the loop condition never becomes False.

This usually happens when the loop variable is not updated correctly.

📝 Key Takeaways
  • The while loop executes statements as long as the condition stays True
  • When the condition becomes False, the loop stops
  • The condition is checked before each iteration
  • An infinite loop occurs when the loop condition never becomes False
  • The while loop is useful when the number of iterations is not known

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.