Introduction
The while
loop in Python is used to repeatedly execute a block of code as long as a given condition is true. This type of loop is useful for situations where the number of iterations is not known beforehand and depends on a condition being met.
Syntax
while condition:
# block of code to be executed
Example
i = 1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
5
In this example, the loop continues to execute as long as i
is less than 6. The variable i
is incremented by 1 in each iteration.
How the while Loop Works
- Initialization: Before the loop starts, you typically initialize a variable (e.g.,
i = 1
). - Condition Check: The condition (
i < 6
) is evaluated.- If the condition is
True
, the block of code inside the loop is executed. - If the condition is
False
, the loop terminates, and the program continues with the next statement after the loop.
- If the condition is
- Update: Inside the loop, you update the variable (e.g.,
i += 1
) so that the condition eventually becomesFalse
.
Using else with while Loop
You can use an else
block with a while
loop. The else
block is executed when the loop condition becomes False
.
Example
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output:
1
2
3
4
5
i is no longer less than 6
Infinite Loop
If the condition never becomes False
, the loop will continue to execute indefinitely. This is known as an infinite loop. You need to ensure that the loop condition eventually becomes False
.
Example of Infinite Loop
while True:
print("This will run forever.")
To stop an infinite loop, you can use a break
statement or interrupt the execution (e.g., pressing Ctrl+C).
Control Statements within while Loop
break
Statement
The break
statement is used to exit the loop prematurely, regardless of the loop condition.
Example
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
continue
Statement
The continue
statement skips the current iteration and proceeds to the next iteration of the loop.
Example
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6
pass
Statement
The pass
statement does nothing and can be used as a placeholder for future code.
Example
i = 1
while i < 6:
if i == 3:
pass
print(i)
i += 1
Output:
1
2
3
4
5
Nested while Loop
A while
loop can be nested inside another while
loop to handle more complex scenarios.
Example
i = 1
while i < 4:
j = 1
while j < 4:
print(f"i = {i}, j = {j}")
j += 1
i += 1
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
Simple Programs Using while Loop
Program 1: Sum of First N Natural Numbers
This program calculates the sum of the first n
natural numbers.
n = 10
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print(f"The sum of the first {n} natural numbers is {sum}")
Output:
The sum of the first 10 natural numbers is 55
Program 2: Factorial of a Number
This program calculates the factorial of a given number.
num = 5
factorial = 1
i = 1
while i <= num:
factorial *= i
i += 1
print(f"The factorial of {num} is {factorial}")
Output:
The factorial of 5 is 120
Program 3: Reverse a Number
This program reverses the digits of a given number.
num = 12345
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print(f"The reversed number is {reversed_num}")
Output:
The reversed number is 54321
Conclusion
The while
loop in Python is used for executing a block of code repeatedly as long as a condition is true. By understanding how to use the while
loop, along with control statements like break
and continue
, you can write more efficient and flexible code. Nested while
loops and the use of an else
block with while
further enhance the capability of this looping construct. The provided examples demonstrate practical applications of the while
loop in solving common programming tasks.