Python while loop
Created By: chatGPT
In Python, a while loop is used to execute a block of code repeatedly as long as a condition is True. It's essential to ensure that the loop will eventually terminate to avoid creating an infinite loop. Here’s a basic structure of a while loop:
while condition:
# Code to execute
Here’s an example that uses a while loop to count from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1
In this example, the loop continues as long as
count
is less than or equal to 5. After each iteration, we increment the value of count
by 1 using count += 1
.# Output:
# 1
# 2
# 3
# 4
# 5
To terminate a loop prematurely, you can use the break statement. Here’s an example that stops the loop if
count
equals 3:count = 1
while count <= 5:
if count == 3:
break
print(count)
count += 1
This would output numbers 1 and 2, and then the loop is terminated when
count
reaches 3.# Output:
# 1
# 2
If you want to skip the current iteration of the loop, you can use the continue statement. Here’s how you might skip the number 3:
count = 1
while count <= 5:
if count == 3:
count += 1
continue
print(count)
count += 1
In this scenario, when
count
is 3, the loop skips printing and continues to the next iteration. The output will include all numbers except 3.# Output:
# 1
# 2
# 4
# 5