# Python: Beginner’s Notes #05

## While Loop

Similar to a for loop, a while loop can also run some commands repetitively. But the mechanism is a bit different. Let’s take a look at an example below.

`x = 0while x < 3:    print(x)    x += x`

Output:

`012`

In fact, a while loop has the similar logic as an if/else statement with only an `if` branch. The program above have the same effect as the ones below.

`x = 0if x < 3:    print(x)    x += x    # x is 1 nowif x < 3:    print(x)    x += x    # x is 2 nowif x < 3:    print(x)    x += x    # x is 3 nowif x < 3:     # False    print(x)    x += x`

An if/else statement checks the statement and runs the lines below it once if the statement is `True`. However, a while loop runs in the following workflow.

Step 1: Check the statement; Go to Step 2 if `True` and Step 4 if `False`.

Step 2: Run the lines in the while loop.

Step 3: Check the statement again; Go to Step 2 if `True` and Step 4 if `False`.

Step 4: Stop.

Simply speaking, a while loop repeats the commands as long as the statement is `True` . So let’s take a look at the example above.

`x = 0while x < 3:    print(x)    x += x`

The initial value of `x` is `0`. So the statement in the while loop, `x < 3`, is `True`. It runs the lines below. After one round, `x` becomes `1` and the statement is still `True`. It repeats again and again until `x` becomes `3`. At this point, the statement becomes `False`. The while loop stops.

Since a while loop repeats based on a statement, it may never stop in some cases as below.

`# Case 1x = 0while x < 3:    print(x)# Case 2x = 0while x < 3:    print(x)    x -= x`

In Case 1, the value of `x` is not changed at all in the while loop. In Case 2, the value of `x` is decreased by `1` every time it goes through the while loop. In both cases, `x` will be smaller than `3` forever.

Note: If your Python editor does not response when you run the program, there will be a possibility that your while loop is infinite.

Similar to a for loop, we can use `break` and `continue` in a while loop. It works in the same way. (For more information `break` and `continue`: Please visit https://medium.com/@kael19930923/python-beginners-notes-04-d8feddb2034d)

With `break`, we can write a while loop in another way as below.

`x = 0while True:    print(x)    x += x    if x >= 3:        break`

In this case, the statement is always `True`, which makes it an infinite while loop. But we have an if/else statement to execute `break` when `x >= 3` is `True`. Since sometimes there could be multiple conditions that we want to stop a while loop, it may make our codes more readable, instead of writing all conditions as a single statement after the `while`.

# Difference between a while loop and a for loop

Here is a common question from most of beginners: When should I use a for loop and when should I use a while loop?

The most significant difference between them is: For a for loop, we know the number of rounds we are going to repeat the commands, whereas for a while loop, sometimes we don’t know that but we know in what condition the loop should stop.

There are two cases below for us to decide whether a for loop or a while loop should be use.

Case 1: Print `x**2`, from `x = 0` to `x = 9`(increment by 1).

Case 2: Print `x**2`, from `x = 0` (increment by 1) until `x**2 > 789`.

For Case 1, we know that we’re going to `print(x**2)` for 10 times, from `x = 0` to `x = 9`. So we can write a program as below.

`for x in range(10):    print(x**2)`

For Case 2, by calculation, we can find out how many times we need to `print(x**2)` until `x**2 > 123`. But we don’t have to bother it with a while loop as below.

`x = 0while x**2 <= 123:    print(x**2)    x += 1`

Although, if we’re familiar with `break`, we can also write a for loop as below to fulfill the requirement as effective as a while loop.

`for x in range(10000):    if x**2 > 123:        break    print(x**2)`

We can simply set a big value in `range()`, to ensure `x**2` will be greater than `123` for sure, and then `print(x**2)` until it breaks.

In conclusion, we use a for loop when we know how many times we need to repeat, or a while loop when we know when to stop it. But one always has a way to do what the other can do.