Welcome to the next step in your Python journey! In the last lesson, you learned how to make your programs smart by using if, elif, and else to make decisions. That's a crucial skill, but many tasks in software—especially in a support context—involve repetition. Think about processing a batch of new tickets, sending a reminder email to 100 customers, or prompting a user for input until they provide a valid response.
This lesson is all about handling that repetition. You'll learn to use Python's two main looping constructs: for loops and while loops. For loops are perfect when you have a known set of items to go through, one by one. While loops are ideal when you need to repeat a task as long as a certain condition holds true. Mastering loops will allow you to automate repetitive work, which is a cornerstone of programming.
The while Loop: Repeating Until a Condition Changes
Let's start with the while loop, as it builds directly on the conditional logic you just learned. A while loop executes a block of code over and over again as long as a specified condition evaluates to True.
The structure is simple:
while condition:
# This indented code will run repeatedly
# ...as long as the 'condition' is True.
A classic use case is a counter. Imagine you want to send a welcome message to the first 5 new users of the day.
The following video from Dave Gray provides an excellent introduction to the while loop. Pay close attention to how a variable is used and changed within the loop to eventually make the condition false and stop the loop.
Python While Loops & For Loops | Python tutorial for Beginners
This video introduces while loops and their basic structure.
Watch the section from the beginning to see how a while loop is constructed and why it's crucial to have a variable that changes inside it to prevent it from running forever.
The most important takeaway is that something inside the loop must eventually change the condition to False. If you forget to increment the counter, like in the example value += 1, you create an infinite loop, where the program gets stuck and never finishes.
A very common and powerful pattern is to create an intentional infinite loop with while True: and then use a conditional check inside to break out of it. This is perfect for situations where you want to repeatedly ask a user for something until they provide valid input or a signal to quit.
Corey Schafer demonstrates this pattern clearly. This is a technique you'll use frequently, for example, in the main loop of your chatbot application.
Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
This video segment explains how to create and manage an intentional infinite loop using while True: and a break statement.
Watch the segment from this part to understand this common programming pattern. Note how break is used to exit the loop when a specific condition is met, and how you can manually stop a program if it gets stuck.
The for Loop: Iterating Over a Sequence
While while loops are great for repeating based on a condition, for loops are designed to iterate over a known sequence of items. This could be the characters in a string, a list of ticket numbers, or a range of numbers.
The official Python documentation provides a concise definition. As you read, notice the syntax for w in words:. This is a very readable way to say, "for each item in my collection, I want to do something."
4. More Control Flow Tools — Python 3.14.0 documentation
This resource from the official Python documentation formally introduces the for loop.
Please read the short section titled for Statements. The example iterates over a list of words, but the same principle applies to iterating over characters in a string.
Looping a Specific Number of Times with range()
What if you don't have a sequence to loop over, but you just want to run a block of code a specific number of times? For this, Python provides the range() function.
range(5)generates numbers from 0 up to (but not including) 5:0, 1, 2, 3, 4.range(2, 5)generates numbers starting from 2 up to 5:2, 3, 4.
This is incredibly useful for tasks like "process the 10 most recent tickets." Corey Schafer's video explains this function very clearly.
Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
This video explains how to use the range() function to control a for loop for a specific number of iterations.
Watch from this section on the range() function. Pay close attention to the fact that the sequence starts at 0 by default and excludes the final number.
Fine-Tuning Your Loops with break and continue
You've already seen break used to exit a while True: loop. Both for and while loops can be controlled with two powerful statements: break and continue.
break: Immediately terminates the loop. No further iterations will run. This is useful when you're searching for something and can stop once you've found it.continue: Immediately stops the current iteration and jumps to the beginning of the next one. This is useful for skipping over items that don't need processing.
For a support chatbot, you might use these like this:
break: In a loop processing user messages, if a message contains "escalate to human," you mightbreakthe loop to transfer the conversation.continue: In a loop checking a list of tickets, if a ticket's status is already 'Closed', you could usecontinueto skip it and move to the next one immediately.
This next segment from Corey Schafer's tutorial provides a side-by-side comparison of break and continue, which is the best way to understand their different behaviors.
Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
This video clearly demonstrates the difference between the break and continue statements within a loop.
Watch from this explanation of break and continue. Try to predict the output of the code in the video before it runs to test your understanding.
Practice Exercise
Let's write a small program to simulate logging new support tickets and counting the high-priority ones. This will combine everything you've learned: while loops, input(), if/elif/else, break, continue, and variables.
Create a new Python file named ticket_logger.py. The program should do the following:
- Initialize a counter variable
high_priority_count = 0. - Start an infinite
while True:loop to continuously accept input. - Inside the loop, prompt the user:
Enter ticket priority (High, Medium, Low) or 'done' to finish:. - Check the user's input:
- If the input is
'done', print a summary message likeTotal high-priority tickets: 3and thenbreakthe loop to end the program. - If the input is
'High', incrementhigh_priority_countby 1 and printHigh-priority ticket logged.. - If the input is
'Medium'or'Low', just printTicket logged.. - If the input is anything else (e.g.,
'Urgent',''), printInvalid priority level. Please try again.and usecontinueto skip to the next loop iteration without logging anything.
- If the input is
Here's a starting template. Try to complete it yourself!
# Initialize a counter for high-priority tickets
high_priority_count = 0
print("--- Ticket Logging System ---")
# Start an infinite loop to accept ticket priorities
while True:
# Prompt the user for input
priority = input("Enter ticket priority (High, Medium, Low) or 'done' to finish: ")
# Check if the user wants to quit
if priority == 'done':
# Print the final count and exit the loop
print(f"\n--- Summary ---")
print(f"Total high-priority tickets: {high_priority_count}")
break
# Check for valid priority levels
if priority == 'High':
high_priority_count += 1
print("High-priority ticket logged.")
elif priority == 'Medium' or priority == 'Low':
print("Ticket logged.")
else:
# Handle invalid input
print("Invalid priority level. Please try again.")
# Skip the rest of this iteration and prompt again
continue
print("System shutdown.")
Run your completed script and test all the different inputs to see how your logic behaves.
Conclusion
You have now added two of the most fundamental tools in programming to your skillset. Loops give your programs the power of automation, turning tedious, repetitive tasks into operations that can be completed in an instant.
Here are the key takeaways from this lesson:
forloops are used to iterate over a known sequence of items.- The
range()function is a handy tool for makingforloops run a specific number of times. whileloops are used to repeat a block of code as long as a condition is true, which is ideal when the number of iterations isn't known beforehand.breakprovides a way to exit a loop immediately.continuelets you skip the current iteration and move to the next.
In our next lesson, we will formally introduce Python lists. You've had a small preview of them in today's examples. Lists are versatile containers for storing collections of data, and for loops are the primary way we interact with them.