Python – Infinite While loop

Python – Infinite While loop

In Python, an infinite While loop is a While loop where the condition is always evaluated to True.

To define an infinite While loop, we can simply give the True boolean value as the condition in While loop.

Examples

In the following program, we write an Infinite While loop to print "Hello World" to standard console output indefinitely, until you interrupt the execution of program.

Python Program

while True:
    print('Hello World')

Instead of the boolean value True, you can also give a condition that always evaluates to True. For example, in the following program, we given the condition 1 == 1 which evaluates to True always.

Python Program

while 1 == 1:
    print('Hello World')

If you are running the application as a console application in the Terminal or Command Prompt, press Cmd+C or Ctrl+C that generates a KeyboardInterrupt, and stops the execution of program.

Uses of Infinite While loop in Python

The following are some of the use cases where infinite While loop can be used in Python programs.

  • Server Applications: In server applications, you often want the server to run indefinitely, continuously listening for incoming connections or processing tasks. An infinite While loop can be used to keep the server running.
  • Game Loops: In game development, an infinite loop is commonly used to create the game loop, which continuously updates the game state and renders it to the screen.

Summary

In this tutorial, we learned about Infinite While loop, some examples that demonstrate how to define an infinite While loop, and use cases for running While loop indefinitely.

Code copied to clipboard successfully 👍