Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
53: While Loops and Loop Control
We've spent a lot of time with for loops, which are great when you know exactly how many items you're dealing with. But in the real world, you often don't know when a task will end. Maybe you're waiting for a user to type "quit," or you're polling an API until a status changes to "complete." For that, we need the while loop.
Wait, why is my terminal frozen?
Let's try to build a simple command-line interface. I want a program that just keeps asking me for a command until I tell it to stop. I'll start with the most basic while loop possible.
while True:
command = input("Enter a command: ")
print(f"Executing {command}...")
If I run this, it works... too well. It asks for a command, prints it, and then immediately asks again. And again. I've just created an infinite loop. Now I'm stuck hitting Ctrl+C to kill the process. The while True: pattern is incredibly common, but it's a dangerous tool if you don't have an exit strategy.
Finding the exit door
I need a way out. The most straightforward way is to change the condition from True to a variable that I can flip. Let's try using a boolean flag.
is_running = True
while is_running:
command = input("Enter a command (type 'exit' to stop): ")
if command == "exit":
is_running = False
else:
print(f"Executing {command}...")
This works. It's safe. But honestly? It feels a bit wordy. I have to initialize a variable outside the loop and then update it inside. In a larger project, tracking the state of is_running across a hundred lines of code can get annoying. There's a cleaner way to just "bail out" of a loop immediately.
Cutting the line with break
Python gives us the break keyword. It tells the program: "Stop this loop right now and move to the next block of code below it." Let's rewrite that same logic without the flag.
while True:
command = input("Enter a command (type 'exit' to stop): ")
if command == "exit":
break
print(f"Executing {command}...")
print("Program shut down successfully.")
Much better. The logic is flatter and easier to read. The loop runs indefinitely until it hits that break statement, at which point it jumps straight to the final print statement.
Skipping the garbage
Now, here is a real-world problem: users are unpredictable. If I just hit Enter without typing anything, my current program says "Executing ...", which is silly. I don't want to stop the whole loop, but I do want to skip the "Executing" part for empty inputs.
I could wrap everything in an if/else, but that leads to "indentation hell" where your code keeps drifting to the right. Instead, I'll use continue. This tells Python to stop the current iteration and jump back to the top of the loop immediately.
while True:
command = input("Enter a command (type 'exit' to stop): ")
if command == "exit":
break
if not command:
print("You didn't type anything! Try again.")
continue
print(f"Executing {command}...")
Notice how the continue prevents the print(f"Executing...") line from running. It effectively says, "This specific attempt was a waste of time; let's just start over from the top."
📋 Practical Task
Build a Limited-Attempt ATM Pin Validator
Write a program that simulates an ATM pin entry system. The goal is to protect the account by limiting the number of attempts.
- Set a secret pin (e.g.,
"1234"). - Give the user a maximum of 3 attempts to enter the correct pin.
- Use a
whileloop to keep asking for the pin. - If the user enters the correct pin, print "Access Granted" and use
breakto exit the loop. - If the user enters the wrong pin, decrement their remaining attempts and tell them how many tries they have left.
- If the user runs out of attempts, the loop should end and print "Account Locked."
There are no comments for now.