Sitemap

Day 7 — While Loops in Python

4 min readMay 11, 2025

--

You may be wondering — why do we need another loop, when we already learned about for loop on Day-5?(if not, check out Day 5 here — it’s a must-read before diving into this!).

Well, if you noticed, in a for loop we need to specify the number of times the loop will run. But what if you don’t know that in advance?

What will you do in situations like:

  • Keep asking the user for input until they type "stop"
  • Run a game 🎮 until the user chooses to quit
  • Loop while a condition stays true

In such cases, we need something more flexible. And that’s where the while() loop comes in.

What Is a While Loop?

The while loop runs a block of code as long as a condition is true. The moment the condition becomes false — the loop stops.

🧱 Syntax:

while condition:
# code to repeat

👉 Example:

count = 1

while count <= 3:
print("Count is:", count)
count += 1

Explanation:
So here, we’ve set a count variable to 1.

Then we run a loop that continues while count is less than or equal to 3 i.e until the condition remains true.

If the condition is true, it will print the value of count and then update it (increase it by 1.If we don’t update it, the loop will run forever — that’s called an infinite loop.)

Once the condition becomes false — i.e., count becomes greater than 3 — the loop stops automatically.

🟢Output:

Count is: 1  
Count is: 2
Count is: 3

The Infinite Loop Trap

Earlier, we saw that when the condition becomes false when count greater than 4, the while loop will automatically stops.
But what happens in a case like this?

while True:
print("The Best")

Here, we’ve given the condition as True, which means we’re telling Python to always keep running the loop.
We haven’t updated the condition, and we also haven’t used a break statement (don’t worry — we’ll talk about that later in this blog).

This creates an infinite loop, meaning the loop will never stop running. So, we need to be careful.
Always make sure to:

  • Update the condition inside the loop
    or
  • Use a break statement to exit manually.

Avoiding infinite loops is super important if you don’t want your program to get stuck forever!

Using not to Reverse Logic

The not keyword simply flips a condition:

  • not True → False
  • not False → True

It’s like saying: “Do this only if it’s not the case.”

👉 Example:

logged_in = False

while not logged_in:
print("Trying to log in...")
logged_in = True

Explanation:

So here, the loop runs only while logged_in is False, because not logged_in becomes True.
And as we know, a while loop runs as long as the condition is True.

Once logged_in becomes True, not logged_in becomes False, and the loop automatically exits.

Exiting Early with break

Sometimes, even when the condition is True, you might want to exit the loop manually — and that’s where break comes in.

The break keyword is like an emergency exit — it immediately stops the loop, even if the condition is still True.

Get Ratnesh’s stories in your inbox

Join Medium for free to get updates from this writer.

It’s super useful when you’re waiting for a specific input, condition, or event to occur and want to exit as soon as it does.

👉 Example:

while True:
command = input("Type 'exit' to stop: ")

if command == "exit":
break

print("You typed:", command)

🟢Output:

Press enter or click to view image in full size

👉Mini Project — Simple Number Guesser

Here, we want to create a program where the user keeps guessing the number until they get it right and if they get it wrong we tell them is there guess more than the defined number or less than the defined number.

So if you’ve understood the logic — go ahead and try coding it yourself!

🪜 Step-by-step Logic:

Step 1:
Set a number the user needs to guess (you can also make it random later).

number = 7

Step 2:
Initialize a variable to store the user’s guess.
We start with any number that’s not equal to the answer, so the loop runs.

guess = 0

Step 3:
Start a while loop that runs until the user guesses it right.

while guess != number:

Step 4:
Take the user’s input inside the loop and convert it to an integer.

guess = int(input("Guess the number: "))

Step 5:
Check whether the guess is too low, too high, or correct:

if guess < number:
print("Too low. Try again!")
elif guess > number:
print("Too high. Try again!")

Step 6:
If the guess is correct, exit the loop and congratulate the user:

print("🎉 You got it!")

Code:

number = 7
guess = 0

while guess != number:
guess = int(input("Guess the number: "))

if guess < number:
print("Too low. Try again!")
elif guess > number:
print("Too high. Try again!")

print("🎉 You got it!")

Bonus Tip: To make the game more fun, replace number = 7 with:

import random
number = random.randint(1, 20)

Now the number will change each time!

Output:

Press enter or click to view image in full size

🎯 Mini Challenge Time!

It’s time to practice your looping logic!

  1. Countdown from 10 to 1
  2. Ask for Name Until User Types It
  3. Add Numbers Until User Types 0

Practice these 3 questions, and if you have any doubts — feel free to drop a comment below. I’ll be happy to help!

Closing Thoughts

The while loop gives you flexibility and control — it lets your program keep running until the moment you decide to stop it.

You’ve now learned how to:

  • Loop based on a condition
  • Use not to flip logic
  • Use break to stop early
  • Create interactive programs that adapt to user input

Today, your code learned how to think and wait.

--

--