Loops
Have you ever needed to repeat an action multiple times, like counting numbers or printing a message repeatedly? Instead of duplicating lines of code, loops simplify the process by automating repetition.
Python provides two main types of loops: for
while
Loops allow you to write a block of code once and execute it multiple times. They are essential for automating repetitive tasks, saving time and effort.
Types of loops
for
Loops: Iterating over a sequence
A for
loop repeats an action for every item in a sequence, such as a list, a string, or a range of numbers.
Syntax:
for item in sequence:
# do something with item
Example:
for number in [1, 2, 3, 4, 5]:
print("This is number:", number)
Explanation: The loop iterates over the [1, 2, 3, 4, 5]
number
takes one value from the list. It prints each value during the process.
Using range()
with for
Loops
range()
If you need a sequence of numbers but don’t have a predefined list, use the range()
Example:
for i in range(5):
print("Hello!")
Explanation: range(5)
while
Loops: Repeating based on a condition
A while
Syntax:
while condition:
# do something
Example:
counter = 1
while counter <= 5:
print("Counting:", counter)
counter += 1
Explanation: This loop prints numbers from 1 to 5. The variable counter
counter
counter <= 5
Controlling Loops
Breaking out of a Loop with break
break
Sometimes, you may need to exit a loop before it naturally ends. Use the break
Example:
for number in range(10):
if number == 5:
break # Exit the loop when number equals 5
print(number)
Explanation: This loop prints numbers from 0 to 4. When number
reaches 5, the break
Skipping steps with continue
continue
If you want to skip the rest of the loop’s code for the current iteration and move to the next one, use continue
Example:
for number in range(5):
if number == 2:
continue # Skip when number equals 2
print(number)
Explanation: This code prints numbers 0, 1, 3, and 4, skipping 2. The continue
Practical examples
Example 1: Calculating the sum of numbers
total = 0
for number in range(1, 6): # Numbers 1 to 5
total += number
print("Total:", total)
Output:
Total: 15
Explanation: The loop adds each number from 1 to 5 to the variable total
Example 2: Password check
password = "secret"
attempt = ""
attempts = 0
while attempt != password and attempts < 3:
attempt = input("Enter password: ")
attempts += 1
if attempt == password:
print("Access granted!")
else:
print("Access denied!")
Explanation: This loop allows the user three attempts to guess the password. If the correct password is entered within three tries, it prints "Access granted!" Otherwise, it denies access.
Best practices for Loops
-
Avoid infinite Loops: Ensure conditions in
loops will eventually become false. For example:while
# Infinite loop (avoid!) while True: print("This never ends!")
-
Use descriptive Loop variables: Choose variable names that clearly represent their role.
# Good for student in students: print(student) # Vague for s in students: print(s)
-
Use
efficiently: Customize the range with start, stop, and step values.range()
for i in range(2, 10, 2): # Start at 2, go up to 10, increment by 2 print(i)
Conclusion
Loops are indispensable tools in programming. With for
while
By mastering break
continue