Like its cousin, the for loop, while loops are about repetition. The main difference here is that we can use while loops when we are not sure of how many times repetition needs to take place.

For example, If I wanted to send a message to everyone in my class, I probably know how many students there are. Therefore, I could use a for loop.

However, if I wanted to keep music running in a game until the game was over, that may be a different length of time, based on how skillful the player is.

How does it work

Similar to an if statement, there needs to be a condition in a while loop. for example:

lives = 3

while lives >= 0:
		gameRunning = True

Example

https://replit.com/@bitFez/whileexample1#main.py

https://youtube.com/shorts/yZ4mI6dBMzw?si=uLZ6e2TbXCh0nBGG

Heads up!

It's very important to get your operators correct when using a while loop. You could be left in an infinite loop until your program crashes! See the example below

https://replit.com/@bitFez/whileexample2#main.py

The same could happen if the counter is not incremented/decremented

https://replit.com/@bitFez/whileexample3#main.py

Tasks