
Welcome back! In Part 2, we learned how to make decisions with if, elif, else, and logic. Now itβs time to make your code repeat itself β a superpower every hacker, analyst, or automation wizard needs.
π Part 3: while Loops β Repeat Until a Condition is False
A while loop runs as long as a condition is true:
count = 0
while count < 5:
print("Count is:", count)
count += 1
π§ Think: βWhile this is still true, keep looping.β
π§― Infinite Loops (And How to Escape)
If the condition never becomes false, your code loops forever.
while True:
command = input("Type 'exit' to quit: ")
if command == "exit":
break
breakexits the loop entirelycontinueskips the rest of the current loop and goes back to the top
π Part 4: for Loops β Loop Through Lists, Ranges, and More
A for loop is best when you know how many times to repeat, or you want to go through something like a list or string.
tools = ["nmap", "curl", "burp", "wireshark"]
for tool in tools:
print("Tool:", tool)
You can use for to loop through:
- Lists
- Strings
- Files
- Anything iterable
π’ Using range() to Loop N Times
for i in range(5):
print("Looping:", i)
This will loop 5 times, with i going from 0 to 4.
π Real Example: Password Guess Loop
Letβs say we want to limit login attempts:
password = "hunter2"
attempts = 0
while attempts < 3:
guess = input("Enter password: ")
if guess == password:
print("β
Access granted.")
break
else:
print("β Try again.")
attempts += 1
π§ Loop Tips and Good Practices
- β
Use
forwhen looping through things you know - β
Use
whilewhen you need to repeat until something happens - π§― Always give your
whileloops an exit path - π§Ό Use
breakto stop early, andcontinueto skip a loop round - π§ββοΈ Indentation = life in Python. Keep your blocks clean
βοΈ Coming Up Next: Lists, Indexing, and Looping with Power
Weβll dig into:
- Indexes and slicing
- Building lists dynamically
- Nested loops
- Looping with
enumerate()andzip()
Ready to keep going? Or want a mini challenge to try out loops right now?
Leave a comment