Skip to main content
Published on

While Loop in Python

Share:

Introduction

The while loop is one of the most basic and powerful repetition structures in the Python language. It allows a block of code to be executed repeatedly as long as a specific condition is true.

Basic Concepts of the while Loop

The while loop is used to repeat a set of instructions as long as a specific condition is true. The structure generally takes the following form:

while condition:
  # code to be repeated

Basic Example

counter = 1

while counter <= 10:
  print('Loop number:', counter)
  counter += 1

This loop will print the numbers from 1 to 10.

Difference Between for and while

While the for loop is used to iterate over items in a collection (such as a list or a range), the while loop is used when you want to repeat a block of code based on a condition, without worrying about the specific number of times the code will be executed.

Infinite Loops

One of the precautions to take with the while loop is to avoid creating infinite loops, that is, loops that never end.

'''
while True:
  print('We are facing an infinite loop.')
'''

Conclusion

The while loop offers a flexible way to control the execution of code blocks based on a condition. However, it is crucial to ensure that the condition becomes false at some point, to avoid infinite loops.

Happy coding!