While loop control structure in Python

This post is lesson 12 of 54 in the subject Python Programming Language

1. Using a While Loop in Python

The while loop in python repeatedly executes a block of code while a certain condition is satisfied. The syntax for the while loop is:

while condition:
    # Body of while

If the condition is True, then the statements within the body of the while loop will be executed. If the condition is False, then the statements within the body of the while loop will not be executed.

Note: The Python compiler will understand any value of a condition other than 0 as True. However, None or 0 will be False.

Example:

sum = 0
i = 1
while (i < 5):
    sum = sum + i
    print(i, end=' ')
    i = i+1
print("\nsum = ", sum)

Output

1 2 3 4
sum =  10

We can also use while to iterate through the elements in a list.

fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
    print(fruits[i])
    i = i + 1

Output

apple
banana
cherry

2. Using a While Loop in One Line of Code

We can write the while loop in only one line of code. In this case, if the while body contains multiple statements, the statements are separated by a semicolon (;). Example:

i = 0
sum = 0
while (i < 3): i += 1; print("Welcome to Gochocit.com"); sum +=i
print("sum = ", sum)

Output

Welcome to Gochocit.com
Welcome to Gochocit.com
Welcome to Gochocit.com
sum =  6

3. Using a While Loop with an Else Statement

Similar to the for loop in Python, the while loop can also be used with else. The statements in the else block only execute after the condition of the while loop is False.

Note: In case the while loop has a break statement and the break statement makes the loop exit, the statements in the else block will not be executed.

Example using while loop with else

numbers = [0, 1, 5]
i = 0
while i < len(numbers):
    print(numbers[i])
    i = i + 1
else:
    print("That is all in the numbers list.")

Output

0
1
5
That is all in the numbers list.

For example, using a while loop with break and else

print("#Result 1")
i = 0
while i < 4:
    if(i!=9):
        print(i)
    else:
        break
    i = i + 1
else:  # Executed because break in for is not executed
    print("No Break")

print("#Result 2")
i = 0
while i < 4:
    if(i!=3):
        print(i)
    else:
        break
    i = i + 1
else:  # Not executed as there is a break is executed
    print("No Break")

Output

#Result 1
0
1
2
3
No Break
#Result 2
0
1
2

In the above example, if break in while is executed (making the loop exit), then else will not be executed. However, if there is a break in while but it is not executed, then else will still be executed.

4. Checking Input Values with While Loops

The property of the while loop is to repeatedly execute a block of code until a certain condition is met. Based on this property, we can use while to help check the input value that the user enters. If the input value that the user enters does not meet the requirements, then the user will be asked to re-enter until the requirements are met. Example:

a = int(input('Enter a positive number: '))

while a <= 0:
    a = int(input('Enter a positive number: '))

Output

Enter a positive number: -9
Enter a positive number: -1
Enter a positive number: -2
Enter a positive number: -8
Enter a positive number: -5
Enter a positive number: 7

The while loop helps check a number entered if a <= 0 then continue to enter. Until the user enters a > 0, then it stops.

5/5 - (1 vote)
Previous and next lesson in subject<< For loop control structure in PythonLoops in Python: Using the break, continue, and pass statements >>

Leave a Reply

Your email address will not be published. Required fields are marked *