Skip to content

While Loops

PotatoScript edited this page Feb 27, 2025 · 3 revisions

🔄 Loops in Python - While Loop 🔄

🔹 What is a While Loop? 🤔

A while loop is a way to repeat a block of code as long as a condition is True.

📌 Syntax of a While Loop:

while condition:
    # Code that runs while the condition is True

👉 The condition is checked before each loop cycle.
👉 If the condition is True, the loop continues.
👉 If the condition is False, the loop stops.


1️⃣ Basic While Loop Example 🎯

Let's print "Hello, World!" 5 times using a while loop.

count = 1  # Start at 1

while count <= 5:  # Repeat while count is less than or equal to 5
    print("Hello, World!")
    count += 1  # Increase count by 1 each time

💡 Output:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

✅ The loop runs 5 times because count starts at 1 and stops when count > 5.


2️⃣ Using a While Loop to Count 📊

Let's print numbers from 1 to 10 using a while loop.

number = 1  # Start at 1

while number <= 10:  # Repeat while number is less than or equal to 10
    print(number)
    number += 1  # Increase number by 1 each time

💡 Output:

1
2
3
4
5
6
7
8
9
10

✅ The loop stops when number becomes 11, because 11 <= 10 is False.


3️⃣ Infinite Loop - Be Careful! ⚠️

A while loop must have a way to stop. If not, it never ends! 😱

Example of an Infinite Loop (DON’T DO THIS!)

while True:
    print("This will run forever! 😵")

💥 This loop will never stop because True is always True.

✔️ Fix: Add a Break Condition

count = 1

while True:
    print("This will stop after 5 times.")
    count += 1

    if count > 5:
        break  # Stops the loop

💡 Output:

This will stop after 5 times.
This will stop after 5 times.
This will stop after 5 times.
This will stop after 5 times.
This will stop after 5 times.

✅ The loop stops when count > 5 because of the break statement.


4️⃣ Using While Loop with User Input ⌨️

Let’s ask the user to enter "yes" to continue.

answer = ""

while answer != "yes":
    answer = input("Type 'yes' to continue: ")

print("Thank you! ✅")

💡 Example Run:

Type 'yes' to continue: no
Type 'yes' to continue: maybe
Type 'yes' to continue: YES
Type 'yes' to continue: yes
Thank you! ✅

✅ The loop repeats until the user types "yes".
💡 "YES" doesn’t stop the loop because Python is case-sensitive.

✔️ Fix: Convert to Lowercase

answer = ""

while answer.lower() != "yes":
    answer = input("Type 'yes' to continue: ")

print("Thank you! ✅")

✅ Now, "YES", "YeS", and "yes" all work!


5️⃣ Using While Loop with a Countdown ⏳

Let's count down from 5 to 1 and then print "Blast off!" 🚀

count = 5

while count > 0:  # Repeat while count is greater than 0
    print(count)
    count -= 1  # Decrease count by 1

print("Blast off! 🚀")

💡 Output:

5
4
3
2
1
Blast off! 🚀

✅ The loop stops when count = 0.


6️⃣ Using While Loop with a Random Number Guessing Game 🎮

Let's create a simple guessing game. The user has to guess a number between 1 and 10.

import random

secret_number = random.randint(1, 10)  # Pick a random number
guess = 0

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

print("You got it! 🎉")

💡 Example Run:

Guess a number between 1 and 10: 5
Guess a number between 1 and 10: 3
Guess a number between 1 and 10: 8
You got it! 🎉

✅ The loop repeats until the correct number is guessed.


7️⃣ Using break to Exit a While Loop 🚪

Sometimes, we need to stop a loop before the condition becomes False. We can use the break statement.

🔹 Example: Stopping the loop if the user enters "exit"

while True:
    text = input("Type something (or 'exit' to stop): ")
    
    if text == "exit":
        break  # Stops the loop

print("Loop ended. 🚪")

💡 Example Run:

Type something (or 'exit' to stop): Hello
Type something (or 'exit' to stop): Python
Type something (or 'exit' to stop): exit
Loop ended. 🚪

✅ The loop stops when the user types "exit".


8️⃣ Using continue to Skip an Iteration ⏩

The continue statement skips the rest of the code inside the loop for that iteration, but the loop continues running.

🔹 Example: Skipping Even Numbers

num = 0

while num < 10:
    num += 1  # Increase num first

    if num % 2 == 0:  # If num is even, skip
        continue  

    print(num)  # Only prints odd numbers

💡 Output:

1
3
5
7
9

✅ The continue statement skips even numbers and moves to the next iteration.


✅ Summary

✔️ A while loop repeats as long as the condition is True.
✔️ Use break to exit a loop early.
✔️ Use continue to skip the rest of the loop and move to the next iteration.
✔️ Avoid infinite loops by making sure the condition will become False at some point.
✔️ Use loops with user input, counters, and even games! 🎮

i = 1
while i <= 5:
  print('*' * i)
  i = i + 1
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
    guess = int(input('Guess: '))
    guess_count += 1
    if guess == secret_number:
        print("You won!")
        break #this will immediate terminate the loop
else: # this will executed if the while loop was completed without the break
    print("Sorry, you failed! ")

Clone this wiki locally