Learning Management Platform for Written Tutorial Series.

Python 3 While loop - Break the infinity loop like a pro

Python 3 While loop - Break the infinity loop like a pro

Python While Loop

The while loop executes the same code block as long as a the defined condition is true. If the condition evaluates to false, the the execution is stopped.

The while loop has two implementations while and do... while. We will explore both in this lesson.

Topics to be covered

We will cover the following topics in this tutorial

  • While loop pseudocode
  • While loop syntax
  • Continue statement
  • Break statement
  • Else statement

While loop pseudocode

The pseudocode for the while loop is as follows

condition = true
while condition is true then
	execute block of code
	
	at some point condition is set to false

As you can see from the above pseudocode, the while loop evaluates a condition the executes the block of code until something sets the condition to false. If nothing sets the condition to false then the loop will execute until the second coming of Jesus.

While loop syntax

In python, the syntax for implementing the while loop is as follows

condition = True

while condition:
	print('executed while block')
	#alter condition

HERE,

  • condition = True We set a condition that will be evaluated by our while loop
  • while condition: evaluates our condition and if it is true then the code block for the loop is executed.
  • #alter condition is some logic that works on the loop so that it can evaluate to false in the near future.

Let's now look at a practical example. We will print numbers from 0 to 5 in the terminal using a while loop.

i = 0

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

HERE,

  • i = 0 sets the variable i that we will be used in the condition expression. In our case, it is an integer variable i that has been initialized to the value of 0
  • while i < 5: the keyword while starts the while loop and the expression i < 5 is the condition to be evaluated.
  • print(i) prints out the value of i in the console
  • i += 1 alters the value of the variable i which we are using in the expression that is the condition that is been evaluated. by so doing, our loop will reach a point where the value of i will be greater than 5 and that will cause our loop to stop executing.

Let's look at another slightly more advanced example.

import random

condition = True

while condition:
    n = random.randint(1,7)
    m = random.randint(1,10)

    if (n > m):
        print (f'The winning number is {n}, it was blessed by {m}')
        condition = False
    else:
        print(f'The losing number is {n}, it was jinxed by {m}')

HERE,

  • import random imports the random module
  • condition = True defines a condition that is initialized to True.
  • while condition: starts the while loop that evaluates our condition
  • n = random.randint(1,7); m = random.randint(1,10) generates two random numbers using the random module that range between 1 and 7, and 1 and 10 respectively
  • if (n > m): uses the if statement to check if n is greater than m. If yes then we have a winning number and we set the condition to false. If no then we have a losing number and we let the loop continue executing.

The above code produces results similar to the following.

The losing number is 2, it was jinxed by 8
The losing number is 1, it was jinxed by 5
The losing number is 3, it was jinxed by 4
The losing number is 5, it was jinxed by 10
The losing number is 4, it was jinxed by 5
The losing number is 1, it was jinxed by 1
The losing number is 1, it was jinxed by 6
The losing number is 1, it was jinxed by 9
The losing number is 3, it was jinxed by 4
The losing number is 4, it was jinxed by 6
The winning number is 6, it was blessed by 4

Note: we are working with random numbers so you won't get exact results like the above ones. You can get a single line or more depending on what the random function generated.

Continue statement

The continue statement is used to skip execution of the code beneath the continue statement and move on to the next execution.

The following

i = 0

while i < 15:
    i += 1

    if (i % 2 == 0):
        continue

    print(i)

HERE,

  • while i < 15: starts the while loop and evaluates the condition i < 5.
  • i += 1 increments the variable i by 1
  • if (i % 2 == 0): checks if the value of n is an even number. If its is true then we call the continue function that evaluates the next number. If the value of n is not an even number, we print it out in the console by calling print(i)

The above code produces the following result.

1
3
5
7
9
11
13
15

Break statement

The break statement is used to end a loop prematurely when a certain condition becomes true.

Let's look at a practical example

while i < 15:
    i += 1

    if (i == 5):
        break

    print(i)

HERE,

  • if (i == 5): break checks if the value of i is 5 then aborts the loop using the break statement. Note: the loop condition is i < 15 but because of break the loop ends at exactly 5.

The above code produces the following results.

1
2
3
4

Else statement

The else statement is used to execute a block of code immediately after the loop finishes executing.

The following code demonstrates how it works.

i = 0

while i < 5:
    i += 1

    print(i)
else:
    print('Loop execution has completed successfully')

HERE,

  • i = 0 initializes a variable that we will use in our loop
  • while i < 5: sets the loop condition.
  • else: sets the code that should be executed when the while loop is completed.

Executing the above code produces the following results.

1
2
3
4
5
Loop execution has completed successfully

Summary

The while statement is used to execute the same code repeatedly until a predefined condition becomes true. A while loop works by evaluating a condition which if its true execution continues. If its false then execution stops. For example, you can use a while to repeatedly perform a task until a user clicks a button that says stop.

The break statement is used to end a loop prematurely. The continue statement causes the while loop to ignore the code below the continue statement and evaluate the condition again. The else statement can be used to call code that should be executed immediately after the loop finishes executing.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...