Python While Loop

In coding, loops are designed to execute a specified block of code repeatedly. In this tutorial, we will learn how to construct a while loop in Python, understand its syntax, and explore loop control statements like break, continue, and pass. We'll also cover some exercises to apply these concepts.

Introduction to Python While Loop

The while loop in Python repeatedly executes a block of code as long as a given condition, known as conditional_expression, remains true. If we don't know how many times the loop should run ahead of time, we can use a while loop, which is often referred to as an indefinite loop.

Syntax of Python While Loop

The basic syntax of a while loop in Python is as follows:

while Condition:
    Statement

Condition: This is the conditional_expression that is evaluated before each iteration. If the condition is True, the loop executes the block of code within it.

Statement: This is the block of code that will run as long as the condition is True.

The loop continues until the condition evaluates to False. The statements within the while loop are dictated by indentation. The loop starts with an indented block of code and ends when the first unindented statement is encountered.

Example 1: Printing Numbers from 1 to 10

i = 1
while i <= 5:
    print(i, end=' ')
    i += 1

Output:

1 2 3 4 5

Example 2: Printing Numbers Divisible by 10 or 15 from 1 to 100

i = 1
while i < 101:
    if i % 10 == 0 or i % 15 == 0:
        print(i, end=' ')
    i += 1

Output:

10 15 20 30 40 45 50 60 70 75 80 90 100

Example 3: Sum of cube of the First 10 Natural Numbers

num = 10
summation = 0
c = 1

while c <= num:
    summation += c ** 3
    c += 1

print("The sum of cube is", summation)

Output:

The sum of cube is 3025

Example 4: Multiplication Table using While Loop

num = 10
counter = 1

print("The Multiplication Table of:", num)
while counter <= 10:
    ans = num * counter
    print(num, 'x', counter, '=', ans)
    counter += 1

Output:

The Multiplication Table of: 10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100