🐍 How to Code in Python: Part 3 & 4 β€” Loops and Repeating Tasks

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
  • break exits the loop entirely
  • continue skips 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 for when looping through things you know
  • βœ… Use while when you need to repeat until something happens
  • 🧯 Always give your while loops an exit path
  • 🧼 Use break to stop early, and continue to 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() and zip()

Ready to keep going? Or want a mini challenge to try out loops right now?

Leave a comment