# While Loops¶

One of the fundamental concepts in algorithms is being able to repeat steps or instructions. The while loop is a way of repeating a set of statements until the desired condition becomes false. In Python this looks like:

while condition: code to run if condition is true

The code that is indented following the while keyword will be repeated until the condition expression becomes false.

In [1]:
n = 5
while n > 0:
print(n)
n -= 1
print("done")

5
4
3
2
1
done


## Loop Structure¶

As you can see, the while loop above counts down from 5 to 1 and then finally prints 'done' at once the loop executes. Each iteration of the loop, n is printed out, then decreases by 1. Each time an iteration is completed, the condition of the while statement is checked before another iteration occurs. If the condition is false, the loop exits, and any code following the loop is executed. Therefore, the overall operation of the while loop looks like this:

Image Source

### Do-While (or lack thereof)¶

In [3]:
n = -5
while n > 0:
print(n)
n -= 1
print("done")

done


Notice that the statements inside the above while loop are never executed. This is because the condition of the while loop is checked before the body (code or statements) of the loop is executed. If the initial condition of the while loop is false, the code inside is never executed. Therefore, you aren't necessarily guaranteed one iteration depending on the initial condition. Python, unfortunately, does not have a do while loop. This loop construct is guaranteed to execute the body of the loop at least once before exiting. However, the do while can be imitated in Python by making sure that the while loop condition is initially true:

In [4]:
n = -5
x = True
while x:
print(n)
# n = n - 1
n -= 1
if not n > 0:
x = False
print("done")

-5
done


### The "else" Loop¶

If you haven't noticed, a while loop is just like an if statement that executes the true block of code until its condition becomes false. With that, Python lets you add an else clause to the while loop statement. It operates just like a regular if-else statement where the else block is only reached when the if condition is false:

In [5]:
n = 5
while n > 0:
print(n)
# n = n - 1
n -= 1
else:
print(n)
print("done")

5
4
3
2
1
0
done


## Break and Continue¶

There are many situations where you want to manually control the order of your algorithm without having to rely on condition of the while loop itself. The first construct we have available to do this is the continue statement. The continue statement is like a restart button for the loop. It causes the loop to stop executing statements in the loop body, regardless if there are still statements left to execute. It then goes back to check the while condition all over again.

In [10]:
x = 0

while x <= 9:
print("__beginning of loop__")
x += 1
if x % 2 == 0:
continue
print("Loop1: {}".format(x))

__beginning of loop__
Loop1: 1
__beginning of loop__
__beginning of loop__
Loop1: 3
__beginning of loop__
__beginning of loop__
Loop1: 5
__beginning of loop__
__beginning of loop__
Loop1: 7
__beginning of loop__
__beginning of loop__
Loop1: 9
__beginning of loop__


As you can see, the loop above only prints out odd numbers. The continue statement restarts the loop every time x becomes even.

The other construct we have to control loops in Python is the break statement. The break statement is like an emergency stop button for the loop. It causes the loop to immediately exit, regardless if there are still statements left to execute. This is like the continue statement; however, the break statement does not restart the loop. Lets look at an example with the break and continue statement being used together.

In [15]:
x = 0
y = 0

while x <= 10:
x += 1
if x % 2 == 0:
continue
while True:
y += 1
if y % 2 == 0:
print("Loop2: {}".format(y))
else:
break
print("Loop1: {}".format(x))

Loop1: 1
Loop2: 2
Loop1: 3
Loop2: 4
Loop1: 5
Loop2: 6
Loop1: 7
Loop2: 8
Loop1: 9
Loop2: 10
Loop1: 11


As you can see, the outer loop remains the same. It still prints out only the odd numbers. The inner loop (loop 2) skips all the odd numbers and prints only the even numbers.

## The Game Loop¶

In many situations, loops will depend on user input. A game loop repeats the core functions of a game or program over and over, often including collecting input from the user. Letâ€™s use a basic guessing game as an example.

In [16]:
import random

num = random.randint(0,100)
print(num)
guess = int(input("Please guess a number between 0 and 100: "))

if guess == num:
print("You guessed it right!")
elif guess > num:
else:


40
Please guess a number between 0 and 100: 50


The code above is the core functionality of a simple guessing game without a loop. We create a random number by using the random package and the randint function, which picks a pseudorandom number between two points (inclusive on both the bottom and top end). Then we can get a guess from the user and see if they guessed right, or if we need to give them a hint.

Now lets wrap this up in a loop. We can do this in a couple different styles. The first one is using an infinite loop by using while true and a few selective break and continue statements.

In [19]:
import random

num = random.randint(0,100)
print(num)

while True:
guess = int(input("\nPlease guess a number between 0 and 100: "))
if guess > 100 or guess < 0:
print("Invalid number.")
continue
if guess == num:
print("You guessed it right!")
break
elif guess > num:
else:

3

Please guess a number between 0 and 100: -5
Invalid number.

Please guess a number between 0 and 100: 101
Invalid number.

Please guess a number between 0 and 100: 1

Please guess a number between 0 and 100: 5

Please guess a number between 0 and 100: 3
You guessed it right!


Now we can play the guessing game until we get it right! Notice that there is now a check to make sure the user inputs a number that is within the range of valid input for the game.

We can also do the same loop without any break or continue statements. To do this, we need to move the condition causes us to win the game to the while loop condition. Since we move this check earlier in the algorithm, we need to change our beginning state to have an initial guess. If the program enters the loop, we then need to give the user a hint and get a new guess. If the loop exits, then we can safely assume that the user guessed the right number.

In [21]:
import random

num = random.randint(0,100)
print(num)
guess = int(input("Please guess a number between 0 and 100: "))

while guess != num:
if guess > 100 or guess < 0:
print("Invalid number.")
elif guess > num:
else:
guess = int(input("\nPlease guess another number: "))
print("You guessed it right!")

72
Please guess a number between 0 and 100: 102
Invalid number.