Understanding while Loops

What is a While Loop?

A while loop repeats a block of code as long as a given condition is True. It’s useful when the number of repetitions is not known in advance but depends on a condition.


How Does a While Loop Work?


Basic Syntax

while condition:

    # Code to repeat


Example: Count from 1 to 5

count = 1

while count <= 5:

    print(count)

    count += 1


Output:

1

2

3

4

5



Flowchart of a While Loop


Important Points About While Loops

Example:
while True:

    print("This loop never ends!")


Solution: Ensure the condition changes inside the loop to eventually become False.

Breaking a Loop: Use break to exit a loop immediately.

Example:
while True:

    print("Looping...")

    break



Examples

Example 1: Countdown

number = 5

while number > 0:

    print(number)

    number -= 1

print("Blast off!")


Output:

5

4

3

2

1

Blast off!


Example 2: User Input

password = ""

while password != "python":

    password = input("Enter the password: ")

print("Access granted!")


Example 3: Breaking a Loop

count = 0

while True:

    print(count)

    count += 1

    if count == 3:

        break


Output:

0

1

2



Practice Exercises

Exercise 1: Counting Up

Write a while loop that prints numbers from 1 to 10.

Exercise 2: Guess the Number

Write a program that asks the user to guess a number between 1 and 10. Keep asking until they guess it correctly.

Exercise 3: Sum of Numbers

Write a program that calculates the sum of numbers from 1 to 100 using a while loop.

Exercise 4: Multiplication Practice

Write a program that asks the user for a number and prints its multiplication table until they enter 0.

Exercise 5: Collect Items

Write a program that keeps asking the user to enter an item for their shopping list. Stop asking when they type "done."


Bonus Challenge

Write a program that:


Congratulations!

You’ve learned how to use while loops in Python to repeat actions based on a condition. Practice these exercises to solidify your understanding and become more confident with loops! 🎉