9. Loops in Python (for, while) with Practical Examples
Loops allow you to repeat actions automatically. Instead of writing the same code multiple times, Python loops execute a block of code repeatedly. This is essential for processing data, handling user input, and automating tasks.
1) The for Loop
The for loop is commonly used to iterate over a sequence
such as a list, string, or range of numbers.
Basic Example
for i in range(5):
print("Number:", i)
range(5) generates numbers from 0 to 4.
for loop is ideal when you know how many times to repeat.
2) Looping Through a List
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print("Fruit:", fruit)
The loop automatically takes each item from the list one by one.
3) The while Loop
The while loop repeats as long as a condition is True.
It is useful when you don’t know how many times the loop should run.
count = 0
while count < 5:
print("Count:", count)
count += 1
4) Practical Example: User Login System
password = "1234"
attempt = ""
while attempt != password:
attempt = input("Enter password: ")
print("Access granted!")
The loop continues until the correct password is entered.
5) break and continue
Using break
for number in range(10):
if number == 5:
break
print(number)
break stops the loop completely.
Using continue
for number in range(5):
if number == 2:
continue
print(number)
continue skips the current iteration.
6) Nested Loops
A loop inside another loop is called a nested loop.
for i in range(3):
for j in range(2):
print("i:", i, "j:", j)
Nested loops are often used for working with tables or matrices.
7) Looping Through a Dictionary
student = {"name": "Ali", "age": 22, "grade": "A"}
for key, value in student.items():
print(key, ":", value)
8) Common Beginner Mistakes
- Forgetting to update the counter in a while loop
- Incorrect indentation
- Creating infinite loops accidentally
- Using break incorrectly
Conclusion
Loops are powerful tools that allow you to automate repetition.
The for loop is best when iterating over sequences,
while the while loop is useful for condition-based repetition.
Mastering loops will allow you to process data, build interactive programs, and solve real-world problems efficiently.