Recommended resources
The freely available resources this lesson will direct you to.
In our last lesson, we focused on for loops, which are perfect for repeating tasks a known number of timesβlike processing every item in a list. Today, we'll explore Python's other essential loop structure, the while loop. This type of loop is designed for situations where the number of repetitions is unknown beforehand.
The core idea of a while loop is to repeat a block of code as long as a certain condition remains true. This is fundamental for building interactive programs, a key step toward your goal of creating chatbots. By the end of this lesson, you will be able to write while loops with clear and effective termination conditions to control program flow based on dynamic events, like user input.
When to Use a while Loop Instead of a for Loop
The key difference between for and while loops lies in how they decide to stop. A for loop runs for a pre-determined number of iterations, while a while loop runs until a condition is no longer met. This makes while loops ideal for tasks where you're waiting for something to happen.
The video "Python While Loops - Visually Explained" does an excellent job of clarifying this distinction with a practical example.
Python While Loops: Visually Explained
This video contrasts for and while loops and then demonstrates a classic scenario for a while loop: a user login system where you don't know how many attempts the user will need.
Please watch these two key segments: The Difference Between Them: Pay attention to the explanation of why a for loop isn't suitable for a login system. Simulating a Login System: Observe how the while loop continues to prompt the user as long as the password input is incorrect.
As the video highlighted, the login system is a perfect use case. You can't use a for loop because you have no idea if the user will get the password right on the first try or the tenth. The loop must continue while the input is wrong.
The Anatomy of a while Loop
The structure of a while loop is straightforward. It consists of the while keyword, a condition to be tested, a colon, and an indented block of code (the loop body).
while condition:
# This code block will execute repeatedly
# as long as the 'condition' is True.
Before each iteration, Python evaluates the condition. If it's True, the loop body runs. If it's False, the loop terminates, and the program continues with the code that follows. This cyclical process is visualized perfectly in the following flowchart.

To solidify your understanding of the syntax, let's turn to a clear, written explanation.
While Loops in Python β While True Loop Statement ...
This article from freeCodeCamp provides a concise definition of while loops and breaks down the syntax piece by piece.
Please read the first two parts of the article: The definition of a while loop, which reinforces its use for an unknown number of repetitions. The syntax breakdown, which explains each component of the loop structure.
The Infinite Loop and the Importance of an Exit Strategy
A while loop's greatest strength is also its greatest danger. If the condition never becomes false, the loop will run forever. This is called an infinite loop. To prevent this, your loop body must contain logic that eventually changes the condition to False. This is your loop's "exit strategy."
The "Bro Code" video provides an energetic walkthrough of this concept, showing what happens when you don't provide an exit and how to fix it.
While loops in Python are easy! βΎοΈ
This video demonstrates the difference between a one-time if check and a continuous while check, highlighting the danger of infinite loops and the importance of having an exit strategy.
Watch the following segments: if vs while: See how replacing if with while creates a loop that repeatedly prompts for a name. Infinite Loop Danger: This part shows what happens when the code inside the loop can't change the loop's condition. Age Validation Example: Notice how prompting the user for input again inside the loop provides the necessary exit strategy.
The key takeaway is that something inside the loopβlike getting new user input or incrementing a counterβmust give the condition a chance to become false.
The while True and break Pattern
A very common and clean way to structure while loops, especially for interactive programs, is the while True pattern. Here, the loop's condition is always True, creating an intentional infinite loop. You then use an if statement inside the loop to check for a specific exit condition and use the break keyword to exit manually.
You encountered break in our last lesson with for loops; its function is identical here: it immediately terminates the loop.
This pattern is often preferred because it allows you to get input and then immediately test it, rather than needing a placeholder value before the loop starts. The "Visually Explained" video you watched earlier has a great section on this.
Python While Loops: Visually Explained
This part of the video refactors the login system example to use the while True and break pattern, demonstrating a cleaner and more direct structure.
Watch the final segment on this alternative syntax. Pay attention to how break is used to exit the loop from within.
This structureβa while True loop containing a way to break outβis the engine behind most simple conversational programs.
Application: A Simple Chatbot
Let's apply this directly to your interest in chatbots. The code below shows a simple bot that continuously listens for user input and responds based on keywords. It runs forever until the user says "bye".

Let's break down how this works:
while True:creates a loop that will run forever by default.user = input("You: ").lower()prompts the user for input and converts it to lowercase.- The
if/elifstatements check if the user's input contains certain keywords. if 'bye' in user:checks for the exit condition. If it'sTrue, the bot says goodbye, and thebreakstatement terminates thewhileloop, ending the program.- If no exit condition is met, the
elseblock handles unknown input, and the loop repeats from the top, asking for input again.
This simple script is a foundational building block for the more complex NLP projects you're aiming for.
Your Turn: Practice with a while Loop
Now it's time to build a small program using these concepts.
Task: Create a simple number guessing game.
- At the start of your script, pick a secret number (e.g.,
secret_number = 7). - Use a
while Trueloop to continuously ask the user to guess the number. - Inside the loop, convert the user's input to an integer.
- Use
if/elif/elseto check if the guess is too high, too low, or correct.- If the guess is too high, print "Too high, try again!"
- If the guess is too low, print "Too low, try again!"
- If the guess is correct, print "You got it!", and then use
breakto exit the loop.
This exercise will test your ability to create a while loop that runs until a specific condition is met, combining user input, type conversion, and conditional logic.
# Here's a starting point for your code.
# Fill in the logic inside the loop.
secret_number = 7
while True:
guess_str = input("Guess a number between 1 and 10: ")
guess = int(guess_str)
# Your if/elif/else logic goes here...
print("Thanks for playing!")
Conclusion
In this lesson, you've added the powerful while loop to your Python toolkit. You now have two distinct methods for controlling repetition in your programs.
Here are the key takeaways:
whileloops are for repetition where the number of iterations is unknown in advance. They run as long as a condition isTrue.- A
whileloop must have an exit strategyβa way for its condition to eventually becomeFalseβto avoid an infinite loop. - The
while Trueandbreakpattern is a common and effective way to structure interactive loops, providing a clear exit point from within the loop body. - This structure is the core of simple interactive applications like the chatbot example we explored.
We have now concluded the first module on Python's foundational control flow. You are proficient with variables, conditionals (if/else), and both for and while loops. In our next lesson, we will begin Module 2 by exploring lists and dictionaries. These data structures will allow you to store and organize collections of information, enabling you to build much more capable and interesting programs.