How to Use While Loops in python

A while loop in Python is used to execute a block of code repeatedly as long as a specified condition remains True. It is useful when the number of iterations is not known in advance.

Basic Syntax of While Loop

while condition:
    # Code to execute repeatedly

The loop will continue running until the condition becomes False.

Example 1: Printing Numbers from 1 to 5

num = 1  # Initialize variable

while num <= 5:  # Condition to check
    print(num)
    num += 1  # Increment num

Output:

1  
2  
3  
4  
5  

Explanation:

  • The loop starts with num = 1.
  • It prints num and then increases its value by 1.
  • When num becomes 6, the condition num <= 5 becomes False, and the loop stops.

Example 2: Sum of First N Natural Numbers

n = int(input("Enter a number: "))
sum = 0
i = 1  

while i <= n:
    sum += i  # Add current number to sum
    i += 1  # Increment counter

print("Sum of first", n, "natural numbers is:", sum)

Output:

Enter a number: 5  
Sum of first 5 natural numbers is: 15  

Explanation:

  • The loop runs from 1 to n, adding each number to sum.
  • When i exceeds n, the loop terminates, and the total sum is displayed.

Example 3: Guessing Game using While Loop

import random

secret_number = random.randint(1, 10)
guess = 0

while guess != secret_number:
    guess = int(input("Guess a number between 1 and 10: "))

    if guess < secret_number:
        print("Too low! Try again.")
    elif guess > secret_number:
        print("Too high! Try again.")
    else:
        print("Congratulations! You guessed it right.")

Output:

Guess a number between 1 and 10: 5  
Too low! Try again.  

Guess a number between 1 and 10: 8  
Too high! Try again.  

Guess a number between 1 and 10: 7  
Congratulations! You guessed it right.  

Explanation:

  • The program generates a random number between 1 and 10.
  • It asks the user to guess the number and provides hints if the guess is incorrect.
  • The loop runs until the correct number is guessed.

Example 4: Using Break in While Loop

i = 1

while i <= 10:
    if i == 5:
        print("Loop stopped at:", i)
        break  # Exit the loop
    print(i)
    i += 1

Output:

1  
2  
3  
4  
Loop stopped at: 5  

Explanation:

  • The loop runs from 1 to 10, but when i reaches 5, the break statement stops execution.

Example 5: Using Continue in While Loop

i = 0

while i < 5:
    i += 1
    if i == 3:
        continue  # Skip iteration when i is 3
    print(i)

Output:

1  
2  
4  
5  

Explanation:

  • When i is 3, the continue statement skips the print statement and moves to the next iteration.

Python’s while loop is an essential tool for executing repeated tasks until a condition is met. Whether you’re performing calculations, creating interactive programs, or controlling flow using break and continue, while loops help make your programs dynamic and efficient. Mastering this concept will enable you to handle repetitive tasks with ease.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *