Python While Loops



A more in depth look into Python While loops, additional uses and examples.

The while Loop continuously executes a statement, or a group of statements while a given condition, or conditions holds true.

Syntax:

Be careful while applying the condition in Python while loops, as even a slight error can cause it to go into an infinite loop where it never ends.

while (condition):
     #statement to be executed

Additional Clauses:

Else statement

An additional statement can be added to the while loop’s syntax called the “else” statement. What this does is to execute a certain command(s) once the given condition in the while loop has become false. Basically, its something that runs once the loop has been terminated.

x= 0
while (x < 5):
    print(x)
    x = x +1
else:
    print("Loop over")
0
1
2
3
4
Loop over

Note: The else statement will not trigger if the loop is terminated early with the break statement


Multiple Conditions

You can increase the number of conditions on a while loop with the help of logical operators like and and or.

a = 5
b = 3
while (a > 1) and (b > 1):
     print("a and b are both greater than 1")

Applying Loop Control Statments

We’ll be applying and demonstrating the use of the three loop control statement, break, continue and pass.

Break

The break statement is used to terminate a loop before it’s completion.

while True:
    num = input("Input a positive number")
    if int(num) < 0:
        break

What this code is continuously take input from the user, but will terminate if a negative number is detected. An alternate way of doing this is shown below.

num = 1
while int(num) > 0:
    num = input("Input  positive number")

However, we can’t always get a solution like this, hence why we have the break statement. Common uses for the break statement are to handle unexpected inputs or upon the appearance of errors during execution.

Continue

The continue statement will stop the current iteration of a loop and skip to the next, avoiding any statements in between.

A short example to demonstrate this effect.

x = 0
while x < 5:
    x = x +1
    if x == 2:
        continue
    print(x)
1
3
4
5

The output is missing the number 2, as the continue statement was executed, causing the loop to ignore everything and move on to the next iteration.

Pass

Python’s structure makes it compulsory for code blocks (if else, def, for) to not be empty. Leaving a code block empty will result in an error.

The pass isn’t very commonly used as it doesn’t have many uses, but it’s still something interesting to know. If you want to make a code block, but leave it blank for a while, you can simply put a pass statement in it.

x = 0
while x < 5:
     print(x)
     if x == 2:
         pass
     x = x + 1

As you can see in the example, we’ve put the pass statement in the if statement. Maybe the coder intends to add a block of code in the if statement, but for now he is leaving it empty. Leaving it empty will cause an error however, so used pass as a placeholder.

Extra Examples:

Some examples to help build your concepts and understanding.

Infinite loop problem
x = 0
while x < 5:
    print(x)

This will result in an infinite loop due to the lack of any increment. Since x will always remain 0, the condition will always be true, resulting in an endless stream of 0’s being displayed onscreen.

Calculating factorial
x = 1
sum = 1
while x <= 5:
    sum = sum * x
    x = x + 1

print(sum)    
120

Try making a modification on this program, taking the factorial number n! from the user. Remember to convert to integer before using it.