# Day 18 – While Loops in Python

![](https://cdn.hashnode.com/uploads/covers/664f77938fc1f806b829b90b/8e148c98-14d0-4434-a258-5a2837c24518.jpg align="center")

Welcome to **Day 18 of 100 Days of Python!** 🐍

Today, we are learning about `while` **loops** — one of the fundamental looping mechanisms in Python.

In the previous lesson, we learned about `for` **loops**, which are commonly used when iterating over a sequence or when the number of iterations is known.

A `while` loop works differently. It repeatedly executes a block of code **as long as a given condition remains** `True`.

We will also learn:

*   How a `while` loop works
    
*   Updating the loop variable
    
*   Infinite loops and how to avoid them
    
*   `while` with `else`
    
*   The `break` statement
    
*   How to emulate a **do-while loop** in Python
    
*   Understanding the complete `main.py` program
    

* * *

## 📚 What We Will Learn

1.  What is a `while` loop?
    
2.  Basic syntax
    
3.  How a `while` loop works
    
4.  Updating the loop variable
    
5.  Avoiding infinite loops
    
6.  `while` loop with `else`
    
7.  Understanding `break`
    
8.  Do-while loops
    
9.  Emulating do-while behavior in Python
    
10.  Complete Day 18 program
     
11.  Important concepts at a glance
     
12.  Quick revision
     
13.  Key takeaways
     

* * *

# 1\. What is a `while` Loop?

A `while` **loop** repeatedly executes a block of statements as long as its condition evaluates to `True`.

### Basic idea:

```text
Check condition
      ↓
Is it True?
  ↓       ↓
 Yes      No
  ↓        ↓
Execute   Exit loop
body
  ↓
Update variables
  ↓
Check condition again
```

The loop continues until the condition becomes `False`.

### Basic syntax

```python
while condition:
    # statements
```

For example:

```python
count = 5

while count > 0:
    print(count)
    count = count - 1
```

### Output

```text
5
4
3
2
1
```

* * *

# 2\. How Does This `while` Loop Work?

Let's understand the example step by step:

```python
count = 5

while count > 0:
    print(count)
    count = count - 1
```

Initially:

```text
count = 5
```

Python checks:

```python
count > 0
```

Since:

```text
5 > 0 → True
```

the loop body executes.

It prints:

```text
5
```

Then:

```python
count = count - 1
```

changes the value to:

```text
4
```

Python checks the condition again:

```text
4 > 0 → True
```

The process continues:

```text
5
4
3
2
1
```

After printing `1`, the value becomes:

```text
count = 0
```

Now:

```text
0 > 0 → False
```

Therefore, Python exits the loop.

* * *

# 3\. The Importance of Updating the Loop Variable

One of the most important things to understand with a `while` loop is that you usually need to **change something inside the loop that eventually makes the condition false**.

For example:

```python
count = 5

while count > 0:
    print(count)
    count = count - 1
```

Here, `count` decreases every iteration.

```text
5 → 4 → 3 → 2 → 1 → 0
```

Eventually the condition:

```python
count > 0
```

becomes false.

* * *

# 4\. What Happens If We Don't Update the Variable?

Consider this:

```python
count = 5

while count > 0:
    print(count)
```

The value of `count` never changes.

Therefore:

```text
count = 5
```

remains true forever.

The condition:

```python
count > 0
```

will always be:

```text
True
```

This creates an **infinite loop**.

### Infinite loop concept

```text
5 → 5 → 5 → 5 → 5 → ...
```

The loop never reaches a state where:

```python
count > 0
```

becomes `False`.

Therefore, when designing a `while` loop, always ask:

> **What will eventually make the loop condition false?**

* * *

# 5\. Incrementing and Decrementing

Depending on the problem, we may either **increment** or **decrement** a variable.

### Decrementing

```python
count = 5

while count > 0:
    print(count)
    count -= 1
```

This produces:

```text
5
4
3
2
1
```

### Incrementing

```python
count = 1

while count <= 5:
    print(count)
    count += 1
```

Output:

```text
1
2
3
4
5
```

The important point is not whether we increment or decrement.

The important point is that the loop must eventually reach a condition that evaluates to `False`, unless we intentionally create an infinite loop and exit using something such as `break`.

* * *

# 6\. `while` Loop with `else`

Python also allows an `else` block to be associated with a `while` loop.

Example:

```python
x = 5

while x > 0:
    print(x)
    x = x - 1
else:
    print("counter is 0")
```

### Output

```text
5
4
3
2
1
counter is 0
```

Here, the `else` block executes after the `while` condition becomes false.

The flow is:

```text
x = 5
  ↓
x > 0 → True
  ↓
Print 5
  ↓
x = 4
  ↓
...
  ↓
x = 0
  ↓
x > 0 → False
  ↓
Execute else
```

So:

```python
else:
    print("counter is 0")
```

runs after normal termination of the `while` loop.

* * *

# 7\. `while` + `else` and `break`

There is an important detail about `while-else`.

The `else` block executes when the loop terminates **normally because its condition becomes false**.

If the loop exits using `break`, the `else` block is skipped.

For example:

```python
x = 5

while x > 0:
    print(x)

    if x == 3:
        break

    x -= 1
else:
    print("Loop completed normally")
```

Output:

```text
5
4
3
```

The `break` statement immediately terminates the loop.

Therefore:

```python
else:
    print("Loop completed normally")
```

does not execute.

This behavior is useful when we want to distinguish between:

*   the loop finishing normally, and
    
*   the loop being terminated early.
    

* * *

# 8\. What is `break`?

The `break` statement is used to **immediately terminate a loop**.

Example:

```python
while True:
    number = int(input("Enter a number: "))

    if number < 0:
        break

    print(number)
```

If the user enters:

```text
5
```

the loop continues.

If the user enters:

```text
-1
```

the `break` statement executes and the loop terminates.

### Flow

```text
while True
    ↓
Take input
    ↓
Process input
    ↓
Condition for stopping?
   ↙       ↘
 Yes       No
  ↓         ↓
 break    repeat
```

* * *

# 9\. Do-While Loop

Some programming languages provide a dedicated **do-while loop**.

A do-while loop has a special property:

> **The loop body executes at least once before the condition is checked.**

Conceptually:

```text
Execute body
     ↓
Check condition
   ↙       ↘
True      False
 ↓          ↓
Repeat     Exit
```

This differs from a normal `while` loop.

A normal `while` loop checks the condition **before** executing the body:

```text
Check condition
      ↓
   True?
  ↙     ↘
Yes      No
 ↓        ↓
Body     Exit
```

Therefore, if the initial condition is already false, a normal `while` loop may execute **zero times**.

* * *

# 10\. Does Python Have a `do-while` Keyword?

Python does **not** have a dedicated `do-while` statement.

Instead, we can achieve similar behavior using:

```python
while True:
    # code to execute

    if condition:
        break
```

This pattern is commonly used to emulate do-while behavior.

* * *

# 11\. Emulating a Do-While Loop in Python

Consider:

```python
while True:
    number = int(input("Enter a positive number: "))
    print(number)

    if not number > 0:
        break
```

Let's understand it.

### Step 1: `while True`

```python
while True:
```

`True` is always true, so this creates a loop that would continue indefinitely.

### Step 2: Execute the body

```python
number = int(input("Enter a positive number: "))
print(number)
```

The user is asked for a number.

Importantly, this code executes **before** the stopping condition is checked.

### Step 3: Check the stopping condition

```python
if not number > 0:
    break
```

If the entered number is not positive, `break` terminates the loop.

* * *

# 12\. Understanding `not number > 0`

This condition:

```python
not number > 0
```

means:

```python
not (number > 0)
```

For example:

If:

```text
number = 4
```

then:

```text
number > 0 → True
not True → False
```

So the `break` statement does not execute.

The loop continues.

If:

```text
number = -1
```

then:

```text
number > 0 → False
not False → True
```

Therefore:

```python
break
```

executes.

The loop terminates.

* * *

# 13\. Example Execution

Suppose the user enters:

```text
1
4
-1
```

The program behaves like this:

### First iteration

```text
Enter a positive number: 1
1
```

Since `1 > 0`, the loop continues.

### Second iteration

```text
Enter a positive number: 4
4
```

Since `4 > 0`, the loop continues.

### Third iteration

```text
Enter a positive number: -1
-1
```

Now:

```text
-1 > 0 → False
```

Therefore:

```python
not -1 > 0
```

is true, and:

```python
break
```

terminates the loop.

* * *

# 14\. Day 18 `main.py` – Complete Program

Here is the complete program from today's lesson:

```python
i = int(input("Enter a number: "))
print(i)

while i <= 38:
    i = int(input("Enter a number: "))
    print(i)

print("Done with the loop")

count = 5

while count > 0:
    print(count)
    count = count - 1
else:
    print("I am inside else block")

while True:
    number = int(input("Enter a positive number: "))
    print(number)

    if not number > 0:
        break
```

* * *

# 15\. Understanding the First `while` Loop

The first section is:

```python
i = int(input("Enter a number: "))
print(i)

while i <= 38:
    i = int(input("Enter a number: "))
    print(i)

print("Done with the loop")
```

First, the program asks the user for a number.

Then it checks:

```python
while i <= 38:
```

If `i` is less than or equal to `38`, the loop runs.

Inside the loop, another number is requested:

```python
i = int(input("Enter a number: "))
```

This updates the value of `i`.

The loop continues until the user enters a value greater than `38`.

For example:

```text
Enter a number: 10
10
Enter a number: 20
20
Enter a number: 38
38
Enter a number: 50
50
Done with the loop
```

When `50` is entered:

```text
50 <= 38 → False
```

Therefore, the loop terminates.

### Important observation

The first input is taken **before** entering the loop.

Then another input is taken **inside** the loop.

This means the first value determines whether the loop starts at all.

* * *

# 16\. Understanding the Second `while` Loop

The second section is:

```python
count = 5

while count > 0:
    print(count)
    count = count - 1
else:
    print("I am inside else block")
```

Output:

```text
5
4
3
2
1
I am inside else block
```

The counter follows:

```text
5 → 4 → 3 → 2 → 1 → 0
```

When:

```python
count > 0
```

becomes false, the loop ends normally and the `else` block executes.

* * *

# 17\. Understanding the Third `while` Loop

The final section is:

```python
while True:
    number = int(input("Enter a positive number: "))
    print(number)

    if not number > 0:
        break
```

This is the **do-while-style portion** of today's program.

The body executes first, and then the program checks whether it should stop.

For example:

```text
Enter a positive number: 5
5
Enter a positive number: 10
10
Enter a positive number: 3
3
Enter a positive number: -2
-2
```

When `-2` is entered:

```python
not number > 0
```

becomes true.

Therefore:

```python
break
```

terminates the loop.

* * *

# 18\. `while` Loop vs `for` Loop

Both are used for repetition, but they are often used in different situations.

| `for` Loop | `while` Loop |
| --- | --- |
| Commonly iterates over an iterable | Runs while a condition is true |
| Useful when iterating through sequences | Useful when repetition depends on a condition |
| Often used when iteration is determined by a collection or range | Often used when the number of iterations is not known beforehand |
| Example: `for x in range(5)` | Example: `while x < 5` |

Example:

```python
for i in range(5):
    print(i)
```

versus:

```python
i = 0

while i < 5:
    print(i)
    i += 1
```

Both produce:

```text
0
1
2
3
4
```

But the logic controlling the repetition is expressed differently.

* * *

# 19\. Common Mistakes with `while` Loops

### Mistake 1: Forgetting to update the variable

```python
count = 5

while count > 0:
    print(count)
```

This can result in an infinite loop.

* * *

### Mistake 2: Updating in the wrong direction

Suppose we write:

```python
count = 5

while count > 0:
    print(count)
    count += 1
```

The values become:

```text
5 → 6 → 7 → 8 → ...
```

The condition:

```python
count > 0
```

never becomes false.

Again, this creates an infinite loop.

* * *

### Mistake 3: Forgetting `break` in an intentional infinite loop

If we write:

```python
while True:
    print("Hello")
```

there is no natural stopping condition.

If we intentionally use `while True`, we generally need a suitable exit mechanism such as:

```python
break
```

* * *

# 20\. Important Concepts at a Glance

| Concept | Meaning |
| --- | --- |
| `while` | Repeats code while a condition is `True` |
| Condition | Controls whether the loop continues |
| Loop variable | A variable whose value often changes during the loop |
| `while True` | Creates an intentionally infinite loop |
| `break` | Immediately exits the loop |
| `else` with `while` | Runs when the loop ends normally because its condition becomes false |
| Do-while | Executes the body at least once before checking the continuation condition |
| Python do-while | Emulated using `while True` and `break` |
| Infinite loop | A loop that never reaches a terminating condition |

* * *

# 21\. Quick Revision

### Basic `while`

```python
while condition:
    # code
```

### Decrementing

```python
count = 5

while count > 0:
    print(count)
    count -= 1
```

### Incrementing

```python
count = 1

while count <= 5:
    print(count)
    count += 1
```

### `while-else`

```python
while condition:
    # code
else:
    # runs after normal loop termination
```

### Exit using `break`

```python
while True:
    # code

    if condition:
        break
```

### Do-while-style pattern

```python
while True:
    # execute at least once

    if stop_condition:
        break
```

* * *

# 22\. Key Takeaways

*   A `while` **loop** executes code repeatedly while its condition is `True`.
    
*   The condition is checked **before each iteration**.
    
*   The loop variable usually needs to be updated so that the loop can eventually terminate.
    
*   Forgetting to update the relevant variable can create an **infinite loop**.
    
*   A `while` loop can have an `else` **block**.
    
*   The `else` block runs when the loop terminates normally because its condition becomes false.
    
*   If the loop exits through `break`, its `else` block does not execute.
    
*   Python does not have a dedicated `do-while` keyword.
    
*   A do-while-style loop can be created using `while True` and `break`.
    
*   A do-while-style structure guarantees that the loop body executes at least once.
    
*   `break` immediately terminates the current loop.
    

Today we learned how to control repetition using conditions with `while` loops, how `while-else` works, and how Python can emulate the behavior of a do-while loop.

The next step is to keep practicing these loop patterns until the flow becomes intuitive — especially the relationship between **conditions, variable updates, and loop termination**.

* * *

## 📂 Day 18 Resources

%[https://github.com/SriteshSuranjan/100-Days-of-Python/tree/main/18-Day18-While-Loops] 

* * *
