While Loop

Introduction:

  • A while loop in Python is used to execute a set of statements repeatedly based on the result of a boolean condition.
  • The while loop is one of the looping statements in Python.

Syntax:

python
while condition:
    statement(s)
  • while is a Python keyword, condition is a boolean expression, and statement(s) is a block of code.
  • The statement(s) inside the while loop must be indented.

Examples:

  1. Print 1 to N Using While Loop:
    • This example uses a while loop to print numbers from 1 to 4.

      python
      n = 4
      i = 1
      while i <= n:
          print(i)
          i += 1
      
    • Output:

      1
      2
      3
      4
      
    • Explanation: The variable i is incremented in each iteration until it reaches the value of n, at which point the loop condition becomes false.
  2. Break While Loop:
    • This example breaks the while loop prematurely using the break keyword.

      python
      a = 4
      i = 0
      while i < a:
          print(i)
          i += 1
          if i > 1:
              break
      
    • Output:

      0
      1
      
    • Explanation: The loop breaks when i becomes 2, as the condition i > 1 is met.
  3. While Loop with Continue Statement:
    • This example skips an iteration of the while loop using the continue keyword.

      python
      a = 4
      i = 0
      while i < a:
          if i == 2:
              i += 1
              continue
          print(i)
          i += 1
      
    • Output:

      0
      1
      3
      
    • Explanation: The loop skips printing the value 2 and continues with the next iteration.

Exercises:

  1. Print Even Numbers Using While Loop:
    • Write a program to print even numbers from 1 to 10 using a while loop.

      python
      i = 1
      while i <= 10:
          if i % 2 == 0:
              print(i)
          i += 1
      
  2. Use Break in While Loop:
    • Write a program to print numbers from 1 to 5 using a while loop. Break the loop if the number is 3.

      python
      i = 1
      while i <= 5:
          if i == 3:
              break
          print(i)
          i += 1
      
  3. Use Continue in While Loop:
    • Write a program to print numbers from 1 to 10 using a while loop. Skip the number 5.

      python
      i = 1
      while i <= 10:
          if i == 5:
              i += 1
              continue
          print(i)
          i += 1
      

Summary:

  • In this tutorial, we learned how to write a while loop in a Python program, and how to use break and continue statements with a while loop. Practice these examples to become proficient in using while loops in your Python programs!