Making Python Repeat Work โ The Smart Way
In programming, loops help us run code repeatedly without writing the same lines again and again. Whether itโs going through a list, repeating a task until a condition is met, or retrying something a few timesโloops are essential.
Letโs dive deep into how Python handles repetition.
1. ๐ฏ for and while Loops #
โ
for Loop #
Used when you want to iterate over a sequence (like a list, string, or range).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
You know how many times you’re looping? Use for.
๐ while Loop #
Runs as long as a condition is True.
count = 1
while count <= 5:
print("Count:", count)
count += 1
You don’t know how many times you’ll loop? Use while.
2. ๐ฆ Using range() and Iterables #
๐ข range() Function #
range(start, stop, step) gives you a sequence of numbers.
for i in range(1, 6):
print(i)
range(5)โ 0 to 4range(2, 10, 2)โ 2, 4, 6, 8
๐ Iterables #
Strings, lists, tuples, dictionaries, etc., are all iterablesโyou can loop through them.
for letter in "Hannan":
print(letter)
3. ๐ break, continue, and pass #
๐งจ break #
Exits the loop entirely.
for i in range(5):
if i == 3:
break
print(i) # prints 0, 1, 2
โญ continue #
Skips the current loop iteration.
for i in range(5):
if i == 2:
continue
print(i) # prints 0, 1, 3, 4
๐ง pass #
A placeholder. Does nothingโuseful when code is โcoming soonโ.
for i in range(3):
pass # to be implemented later
4. ๐งฑ Nested Loops #
A loop inside another loop is called a nested loop.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Great for:
- Working with 2D arrays
- Printing patterns
- Comparing items in two lists
๐ Real-World Use Case: Password Validator with Retry Limit #
Letโs build a script that:
- Asks the user to enter a password
- Validates it against a saved password
- Allows up to 3 attempts
- Locks the user out after failed attempts
โ Requirements: #
- Loop with retry count
- Input validation
- Use of
break,continue
๐ป Full Code Example: #
# Predefined password
correct_password = "python123"
max_attempts = 3
attempts = 0
print("๐ Welcome to Secure Login System")
while attempts < max_attempts:
entered_password = input("Enter your password: ")
if entered_password == "":
print("โ ๏ธ Password cannot be empty. Try again.")
continue
if entered_password == correct_password:
print("โ
Access Granted!")
break
else:
attempts += 1
remaining = max_attempts - attempts
print(f"โ Incorrect password! Attempts left: {remaining}")
if remaining == 0:
print("๐ You are locked out. Try again later.")
๐ What This Covers: #
| Feature | Demonstrated In Code |
|---|---|
while loop | To repeat login attempts |
break | On successful login |
continue | When input is empty |
| Password check logic | With conditionals |
| Counter logic | Retry limiter |
๐ง Challenge Ideas: #
- ๐ Allow user to reset the password if they know a secret key.
- โณ Add a time delay (using
time.sleep()) between retries. - ๐งฎ Log the number of failed attempts and show it at the end.
- ๐ก Encrypt password using
hashlib.
๐งฉ Summary #
In this section, you learned:
โ
for and while loops
โ
Iterating with range() and iterables
โ
Using break, continue, and pass
โ
How to build a real-world retry mechanism with loops
โ
The basics of building a secure CLI login system
โจ What’s Next? #
Up next in the series:
๐งฐ Functions & Modular Coding
Creating reusable code blocks, parameters, return values, scope, and a use case like a Unit Converter Tool
Want me to write the next one now? Or turn all this into a PDF, blog, or APEX Learning App version? Let me know!