Python while Loops? Green Light!

Python while Loops? Green Light!

Did you play Red Light/Green Light growing up? I did. I still play it, though it’s hard to find adults willing to join me. If you live outside the United States you probably played a version called Statues. But what does this have to do with Python while loops? Allow me to explain…

To play Red Light/Green Light, you and your friends gather in an open space. One of you decides to be It and stands at one end of the space while the rest of you line up at the other end. It then turns it’s back to the group, shouting ‘Green light!’ and the group rushes forward, the goal of which is to reach the other side of the open space or touch It. When It turns back around and shouts ‘Red light!’, everyone must stop and if It sees anyone moving, that person must go back to the beginning.

Python while Loops

That’s also how while loops work in programming. This is what a Python while loop looks:

We can think of while loops like repeating if statements:

You get the idea…

While loops are useful when we want to maintain a state until a certain condition is met or until some external event occurs, such as the light suddenly turning red. Then you best FREEZE!

Python while Loops and Boolean Logic

If you love playing video games, like I do, and if you’re as bad at games as I am, then you probably see this all the time:

This very simple countdown is a while loop. You can write it like this:

What’s this count-=  business? This is called the decrement operator. It’s most useful in a loop because each time we use it, it subtracts 1 from the value it is operating on. Create a new file,, and run the following program:

When we begin the while loop, count is equal to 10. We then subtract 1, which leaves us with 9. But 9 is still greater than zero, so we take it from the top and run the loop again and again until count is equal to zero.

We can also add to our value in a loop with the increment operator. All we need to do is make a few simple changes to the example above:

Python while loops are a simple means to introduce complexity into your programs. If you choose to Continue, join us in the next tutorial where we build upon the count example and write an interactive program.

Python while Loops? Green Light! was posted by on . Jared likes to make things. He really wants you to watch The Hello World Program so you can learn the skills you need to build an awesome future. His contributions to the show include puppetry, 3D animation, doodling and speaking in a bad British accent. And yes, that is a fox sitting on his face.

Discuss this article in the Comments below, or and it with your friends. Learn more about Python by subscribing to The Hello World Newsletter .

Join the Discussion

Subscribe to our Mailing List

Stay up to date on the latest videos and tutorials with our monthly newsletter

The email entered is invalid