Loops let a program repeat a set of instructions without writing the same code over and over. Python provides two main kinds: the for loop, which iterates over a sequence such as a list, string, or range of numbers, and the while loop, which repeats for as long as a condition remains true.
Lets cover the syntax and use of both loops, along with the tools that control and extend them: break and continue for altering loop flow, and range() and enumerate() for counting and tracking position.
For loops
A for loop is used for iterating over a sequence object (e.g. a list, a tuple, a dictionary, a set, or a string).
Syntax of a for loop
For control_variable in condition:
Statement
- The python for loop is declared using the *for * keyword.
- The control variable is a variable used to temporarily hold an item from the sequence that is currently being looped over.
- The statement is the instruction that the loop executes on each item in the sequence, you can have multiple statements to be executed.
Example:
Consider a list of names, we can use a for loop to print each name as follows:
names = ["Alice", "Brian", "Jane", "David"]
for name in names:
print(f"Good Morning, {name}")
This will output :
Good Morning, Alice
Good Morning, Brian
Good Morning, Jane
Good Morning, David
A for loop iterates over all the items, while performing the specified statements on each item, the loop then closes after the last item in the sequence.
Example:
Consider a list of transaction amounts, we can use the for loop to iterate over the list and add the amounts together to find the total as below:
transactions = [1500, 3000, 800, 12000, 450, 2700]
total = 0
for amount in transactions:
total += amount
print(f"Added KES {amount}, running total is {total}")
print(f"The total is {total}")
This outputs :
Added KES 1500, running total is 1500
Added KES 3000, running total is 4500
Added KES 800, running total is 5300
Added KES 12000, running total is 17300
Added KES 450, running total is 17750
Added KES 2700, running total is 20450
The total is 20450
Breaking the loop
There are cases where one might need to interfere with the operation of the loop based on certain conditions. Python provides two ways to implement this: Break and Continue.
Break
The break statement fully stops the execution of a loop when it is encountered.
Example:
Consider a list of numbers, we want to find the number 2 in the list. We can use a for loop to iterate over the list and add a condition where if the number 2 is found, we end the loop using the Break statement.
numbers = [3,7,2,9,4]
for n in numbers:
if n == 2:
print(f"Found it !")
break
print(f"Checking for 2 : found {n}")
This outputs :
Checking for 2 : found 3
Checking for 2 : found 7
Found it !
Since 2 is the third item in the numbers list, once it is found the loop is terminated by the break statement and the remaining numbers in the list are not checked.
Continue
The continue statement makes the loop skip the current loop iteration and skip to the next iteration.
Example:
Consider another list of numbers from 0-10, we want to print all the numbers except the number 5, we can use the continue statement to skip the iteration by using the IF condition to check for the number.
numbers = [1,2,3,4,5,6,7,8,9,10]
for n in numbers:
if n == 5:
continue
# using 'end=" "' to add a space between the printed numbers
print(n, end=" ")
print()
This outputs :
1 2 3 4 6 7 8 9 10
Unlike with the break statement, when the condition for the continue statement is met, only the current iteration of the loop is skipped and the loop is run to completion.
Range() function
You can use the range function to specify the number of iterations you want the for loop to perform.
The range function starts from 0 by default and increments by 1 unless specified otherwise.
Example:
We can use a for loop with the range() function to find the square of numbers from 0 to 5 as follows.
for i in range (1, 6):
square = i ** 2
print(f"{i} squared is {square}")
This outputs :
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
Enumerate function
The enumerate() function in Python is used to iterate over an iterable while keeping track of both the index and the value and returns the pairs in the form (index, element).
We can use the enumerate function in a for loop to keep track of the iterations.
Syntax of enumerate function
enumerate(iterable, start)
- The iterable is the sequential object that is being looped over.
- The start dictates the starting value that the indexing starts.
Example:
Consider a list of students, we can use enumerate to print out the names of the students as well as the position of the students by the index, as follows:
students = ["Alice", "Brian", "Jane", "david" ]
for index, name in enumerate(students, start = 1):
print(f"{index}. {name}")
This outputs :
1. Alice
2. Brian
3. Jane
4. david
While loop
A while loop executes the statement as long as the condition evaluates to True.
Syntax of While loop
WHILE Condition:
Statement
The condition is evaluated before each iteration and it returns either True or False. If it returns True the statement is executed then the condition is checked once more.
This runs indefinitely thus you must ensure that the statement can change the condition, to prevent an infinite loop.
Example:
Consider a an example where we need to count up from 0 and stop if the count reaches 4, as follows:
count = 1
while count < 5:
print(f"Count: {count}")
# updating the condition
count += 1
This outputs :
Count: 1
Count: 2
Count: 3
Count: 4
While True loop
This is an application of the while loop where the condition is always True, there is no direct way to update the condition, thus the loop is closed by adding a condition in the loop that calls the break statement.
Example:
Consider a scenario where one needs to enter a PIN to access their bank account, and can only attempt to enter a PIN 3 times, We can use a while true loop to implement it as follows:
# expected pin
correct_pin = "7854"
attempts = 0
max_attempts = 3
# counting the number of attempts
while attempts < max_attempts:
pin = input("Enter your pin: ")
attempts += 1
# if PIN is correct, closing the loop
if pin == correct_pin:
print("Access granted: Welcome.")
break
# if pin incorrect, count attmepts remaining
else:
remaining = max_attempts - attempts
if remaining > 0:
print(f"Wrong PIN. {remaining} attempts left.")
# If out of attempts and pin incorrect
if attempts == max_attempts and pin != correct_pin:
print("Card blocked. Please visit branch!")
In this case the loop will always ask a user to enter a PIN until they either enter the correct PIN or run out of attempts, then the loop closes.
Conclusion
Loops are a core tool for automating repetitive work in Python. The for loop is the natural choice when you know what you are iterating over, whether that is a list, a string, or a range of numbers. The while loop fits cases where the number of repetitions depends on a condition, such as validating a PIN entry.
Break and continue give you finer control over the flow of a loop, while range() and enumerate() make counting and position tracking simple. Together, these tools let you handle most repetition tasks cleanly.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.