Python Day #5: How While Loops Actually Work in Python
Learn how Python while loops work with simple, step-by-step examples. Master loop logic, conditions, and flow control—perfect for beginners and coders alike.
Welcome back to the Python Roadmap to Success, where I am giving all my readers a fair chance at learning Python the right way, following a proven roadmap that I’ve structured and taught for over the last four years.
In our last article we covered the fourth phase in the Roadmap to Success, it covered Advanced Conditional Statements with Logical Operators.
In this lesson, we are going to expand into the next step of managing flow with code. You are going to be introduced to the While Loop. This is the loop we use when we do not know how many times we want to repeat.
Over the last 8+ years I’ve been teaching full-time around the world which has given me the unique opportunity to work with over 1,500+ students. The last four years I’ve been teaching Python full-time. Breaking down complex topics, step by step.
I’ve spent this time curating a structured learning path that ensures my students have the greatest chance of success and don’t just learn but actually master Python as well as their logical thinking and problem solving.
Every week you’ll be introduced to a new topic in Python, think of this as a mini starter course to get you going and allow you to have a structured roadmap that actually builds to create you a solid foundation in Python. Join us today!
In this article, let’s just assume you’ve been following along on my series, The Python Roadmap to Success and have read the previous articles.
Today will continue to build on our last two lessons where you have been working with conditionals and expressions. What do conditional statements and while loops have in common? They both require some type of expression.
One point I should note is, spend time digesting these when I write them, after six weeks most of my posts are automatically put behind a paywall.
If you haven’t subscribed to my premium content yet, you should definitely check it out. You unlock exclusive access to all of these articles and all the code that comes with them, so you can follow along!
Plus, you’ll get access to so much more, like monthly Python projects, in-depth weekly articles, the '3 Randoms' series, and my complete archive!
I spend a lot of my week on these articles, so if you find it valuable, consider joining premium. It really helps me keep going and lets me know you’re getting something out of my work!
Thank you for allowing me to do work that I find meaningful. This is my full-time job so I hope you will support my work by joining as a premium reader today.
👉Only this next month for Mothers & Fathers Day, I am offering my readers a 30% off on all annual subscriptions! Show your parents you care about your career, thanks mom and dad…
If you’re already a premium reader, thank you from the bottom of my heart! You can leave feedback and recommend topics and projects at the bottom of all my articles.
👉 I genuinely hope you get value from these articles, if you do, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
The Idea of Code Automation
As programmers, we want to be lazy. Yes, you read that right. This is something I teach my students, and before you think “Oh my god, that is not good,” hear me out.
Of course I do not want you to take the easy way or lazy way out, as this would often lead to bad code. But the whole idea of this saying is, if something can be automated or repeated to save time, you should be doing this.
The while loop is one of the two loops we use in Python. This is the first loop we are going to work with as it builds nicely from the last two lessons. Not only will use be able to use expressions as with conditional statements, but you will also learn a new way of thinking.
There are plenty of times in code where we have some task that we know we want to repeat, this could be something simple like collecting information from a user until they say stop or something more advanced like ensuring the server is refreshing consistently.
By creating a loop to handle this, you don’t need to write endless code. You can write a small block of code that will repeat until something becomes False
.
That’s the golden rule here. A while loop will run forever until the expressions becomes False
. In plain English, we’d say: Repeat this code while this is True, when this becomes False, then stop.
👉 I genuinely hope you get value from these articles, if you do, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
The While Loop in Action
As I said in the above we can structure out a While Loop when we want something to repeat essentially forever. But keep in mind, we never actually want this. You should always have a way to end the While Loop.
If there is no end to the loop, often times this overruns your computer and slows things down, eventually just freezing things up. So remember to always have a way to end the loop.
To begin writing a loop we now introduced the Python keyword: while
. This is used as the start of the loop. The while
is then followed by an expression. While this expression is True, run the loop. Otherwise, stop running the loop.
In my above code, this is a rather simple loop that I thought up. I wanted to showcase two objectives here. The first one being an expression that is based on our input.
You can enter a country, everything time you enter a country the loop will then print off the country you entered. It follows by asking for another country, you can see that every time the loop runs, at the very end I put the same input.
This is so that when the loop gets to the end, we can send it back to the start again by asking for another input. This is also the way that the loop with break or stop. When I enter “0” as my input the expression: country != “0”
becomes False
, so the loop will stop.
Another key aspect I wanted to show was the use of a counter variable. These are common with loops to keep track of how many times the loop has ran or a way for use to store and count countable information.
I made a variable called, counter
. It begins with the value of 1. Every time the loop runs, I print off the variable, then I increase the value of the variable as well. So if I run this code 10 times the value of the counter variable at the end will be 10.
👉 If you get value from this article, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
Blending Loops with Conditions
The goal of this section is for you to start to see how you can blend different lessons and topics we have covered together in your code. Inside a loop it is common that we have conditional statements, so our loops can run and then you can check conditions as they run.
Yes, a loop could be nested inside of a conditional statement, but it is more common to see statements nested inside loops. Let’s take a look at some code so see how we can merge our past lessons with while loops.
Before you go on reading, I want you to look at the code. Try answering these questions first. How many expressions am I using in the code? What are the expressions used in the code? How many times will the loop run? How do I stop the loop from running?
I hope you were able to answer the above. In total I am using three different expressions, one of them is the loop expression the others are a piece of the conditional statement.
Theoretically this code could run forever, that’s if you are terrible at guessing… The only way to stop this loop would be to guess the correct number, which is 7.
This loop begins running on its own without an input. This is because I set the values to the variables used in the while loop expression at the top. The code translate to: while 0 is not equal to 7, run the loop.
As soon as the loop begins to run, the user is asked to enter an input. We take the number the user enters and then run it through the conditional statement.
You are either too low or two high. So if either of the first two conditions are met we’d see these “hints”. When we guess the number 7, the else clause is ran. Then the value of the guess variable is updated to guess = 7
.
This means that our original expression of: guess != secret_number
changes as the expressions evaluates as False when we guess correctly!
👉 If you get value from this article, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
It’s Time You Learn to Think like a Developer
Most people waste months bouncing between tutorials and still feel lost. That is not going to happen to you, at least not on my watch!
👉 I’m giving you my exact system that’s been proven and tested by over 1,500 students over the last 4+ years with a limited time offer!
My Python Masterclass gives you a clear roadmap, hands-on practice, and expert support—so you can gain Python fluency faster and with confidence.
Here’s What You Get:
✅ 135+ step-by-step lessons that make learning easy
✅ Live Q&A & 1-on-1 coaching (limited spots!)
✅ A private community so you’re never stuck
✅ Interactive tests & study guides to keep you on track
No more wasted time. No more confusion. Just real progress.
Take your career to new heights—secure your spot today!
P.S - Save 35% with the Code: pythonsummer35
🎁 - Get a free one-on-one coaching session with any Masterclass!
Still hesitant?
Go through the entire Masterclass, complete all material, and attend the Q&A's, if you still feel like your struggling I'll personally work with you one-on-one until you're confident!
Breaking out of a Loop
Alright, I will finally touch on a new keyword that we specifically use with loops. This is the Python break
statement. The break statement allows you to stop a loop dead in its tracks, ending the loop when it hits this piece of code.
The break statement is great for search problems, input validation, menu systems, or infinite loops that should stop once a target is met. It also helps make our code more readable and avoids unnecessary looping.
while True
creates an infinite loop and keeps the loop running until it is told to stop. Now personally I do not like using True as the expression, I always try to have an expression that I can tell to become false or that will naturally become false over time.
But nonetheless this is used in code. You can see that every time the loop runs the counter variable attempts is increased by one. The purpose of this program is to give a user three chances at entering the correct password.
If you miss three times, then attempts = 3
. The conditional statement if
attempts >= 3
would become True
with the code block running. This code block has the break
statement. When Python sees this break statement it kills the loop in it’s tracks, thus ending the program.
Guys, with every article comes great responsibility. You should be taking what you learn in these lessons to start building problems and projects before we get to the next lesson.
This is practice, this is the best way to get good at Python faster. I’ve structured this out in a way I know works, so use this to your advantage to keep up with my series The Python Roadmap to Success!
👉 If you get value from this article, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
My Best Starter Resources
Here are the best resources I have to offer to get you started with Python no matter your background! Check these out as they’re bound to maximize your growth in the field.
Code with Josh: This is my YouTube channel where I post videos every week designed to help break things down and help you grow.
Zero to Knowing: My Python Masterclass platform designed from 8 years teaching experience and that has helped over 1,500+ students succeed with Python. (All my readers unlock a limited time, 35% discount, use code: pythonsummer35)
My Books: Maybe you’re looking to get a bit more advanced in Python. I’ve written 3 books to help with that, from Data Analytics, to SQL all the way to Machine Learning.
The Nerd Nook: This is where you are right now! I write here multiple times per week with the sole goal of breaking down this larger than life topic to help you excel and learn Python faster than you thought was possible.
This article will be a piece to a larger roadmap but will go behind a paywall after 6 weeks! To help support my work in teaching others consider joining as a premium reader to unlock all these articles, monthly Python projects and in-depth dives.
Wrapping Up Lesson Five
So, that’s the deal with while
loops in Python. They’re a simple but powerful way to keep your code running until something changes.
Once you get the hang of setting up the right condition and making sure the loop eventually ends, they’re great—especially when you don’t know exactly how many times something needs to happen.
The best way to get better at them? Just try stuff out. Mess around with your code, break it, fix it, and see what happens. That’s how you really learn.
But please remember, you need to have a way to “break” or end the while loop. The last thing you want is an endless loop, these are no bueno.
Stick with it, and while
loops will start to feel like second nature.
Let’s keep moving forward with Day #6 next week.
Hope you all have an amazing week nerds ~ Josh (Chief Nerd Officer 🤓)
👉 If you’ve been enjoying these lessons, consider subscribing to the premium version. You’ll get full access to all my past and future articles, all the code examples, extra Python projects, and more.