Using for and while loops in Python
Now that Python can make decisions, how do we apply those decisions repeatedly?
In the last article, we learned how to guide Python through multiple levels of decision-making using nested if statements. But making decisions is only part of what makes Python pretty powerful.
Picture this: You've just landed your first data analysis task. Your dataset contains 9,000 respondents, and you need to perform the same check on every single record. After writing the same line of code a few times, and dodging errors, you stop and think: There has to be a better way than copying and pasting this thousands of times... right?
There is. It's called a loop, and by the end of this article, you'll know exactly how to use one, and get that task done in a fraction of that time.
The FOR Loop
A for loop is used to repeat a block of code a specific number of times or to iterate over a sequence, such as a list, a string, or a range of numbers.
The general syntax of a for loop looks like this:
for variable in sequence:
# Code to repeat
Where;
-
for: Indicates the beginning of the loop -
variable: Stores the current value during each repetition. You can name it anything meaningful (number,student,county,letter, etc.). -
in: Tells Python to go through each item in the sequence. -
sequence: The collection being looped over, such as a range(), list, or string. -
:Marks the beginning of the loop body. -
Indentation: Indicates code blocks that are in the loop. Everything indented below theforstatement is repeated.
Example 1: Looping over a range
for number in range(5):
print(number)
The Result:
0
1
2
3
4
What happens step by Step:
- Python reads the statement
range(5), which produces the numbers 0, 1, 2, 3, and 4. - The first value, 0, is assigned to the variable
number. -
Python executes the indented code and prints:
0 Python returns to the top of the loop, assigns the next value (1) to
number, and prints it, the process continues for 2, 3, and 4.Once there are no more values left in the range, the loop ends and the program moves to the next line of code.
A quick note about range()
You may have noticed that
range(5)prints the numbers 0 to 4, not 5. That's because the value passed to range() is the stopping point, and Python does not include it. In other words,range(5)means start at 0 and stop before 5.
Example 2: Looping over a list
students = ["Faith", "Sheila", "Bryan", "Sharon"]
for student in students:
print(student)
Example 3: Combining a for loop and conditional if statement
temperatures = [22, 35, 18, 40, 29, 15, 33]
for temperature in temperatures:
if temperature > 30:
print(f"Temperature is: {temperature}")
else:
print(f"Temperature is: {temperature} (below 30)")
Output:
Temperature is: 22 (below 30)
Temperature is: 35
Temperature is: 18 (below 30)
Temperature is: 40
Temperature is: 29 (below 30)
Temperature is: 15 (below 30)
Temperature is: 33
We've seen how for loops make it easy to repeat a block of code when we know what we're looping over, whether that's a range of numbers, a list, or another sequence. But what happens when we don't know in advance how many times a task needs to be repeated? That's where the while loop comes in.
The WHILE loop
The while loop repeatedly executes a block of code as long as a specified condition remains True. Once the condition becomes False, the loop stops.
The general syntax of a while loop looks like this:
while condition:
# Code to repeat
Where:
-
while: Indicates the start of thewhileloop -
condition: The expression that evaluates to eitherTrueorFalse -
:Marks the beginning of the loop body. -
Indented code: The block of code that is repeatedly executed for as long as the condition remains
True.
Let's see how this works in practice
Example 1: printing the numbers from 1 to 5.
count = 1
while count <= 5:
print(count)
count += 1
The Result:
1
2
3
4
5
What happens step by Step:
- The
variablecount is initialized with the value1. Python checks the condition
count <= 5.Since 1 is less than or equal to 5, the condition isTrue, so the loop begins.-
The statement
print(count)is executed, displaying:1 The line
count += 1increases the value of count by 1, changing it from 1 to 2.Python returns to the top of the loop and checks the condition again. Since 2 <= 5 is still
True, the loop repeats.This process continues until count becomes 6. At that point, the condition count <= 5 evaluates to
False, so the loop stops and the program moves on to the next line of code.
Why do we need count += 1/count = count + 1?
Without this line, the value of count would never change. It would remain 1, meaning the condition count <= 5 would always be True. As a result, Python would keep printing 1 forever, creating an infinite loop.
For Example:
count = 1
while count <= 5:
print(count)
The Result:
1
1
1
1
1
...
The loop never ends because count is never updated. Since the condition always remains True, Python keeps executing the loop forever. This is called an infinite loop.
Every while loop should have a stopping condition so that it knows when to stop.
Let's do a few more examples that demonstrate how while loops are commonly used.
#Q1: You have a starting balance of 5k, and you are withdrawing 1000. So you can keep withdrawing as long as the balance is greater than withdrawal
mpesa_balance = 5000
withdrawn_amount = 1000
while mpesa_balance >= withdrawn_amount:
new_balance = mpesa_balance - withdrawn_amount
print(f"Request successful.Your new Balance is: Kshs: {new_balance}")
mpesa_balance -= 1000
print(f"You have insufficient funds. Your Balance is: Ksks: {new_balance}")
# Q2. A savings account starts with Ksh 1,000. It earns 10% interest every month. How many months does it take to reach Ksh 2,000? Print the balance each month.
start_amount = 1000
interest = start_amount * 0.1
month = 0
while start_amount <=2000:
interest = start_amount * 0.1
start_amount = interest + start_amount
month += 1
print (f"After {month} months, your interest is {interest}. The account balance is {start_amount}")
Conclusion
At the beginning of this article, we imagined having to process thousands of survey responses without writing the same code over and over again. As we've seen, loops provide a much more efficient solution.
Whether you use a for loop when you know what you're iterating over, or awhile loop when repetition depends on a condition, both allow Python to automate repetitive tasks efficiently and with far less effort and error than doing them manually.
As you continue learning, try modifying the examples in this article and create a few of your own. Remember, the more you practise, the more natural it will become to recognise when a loop is the right tool for the job.
Up Next...
We've learned how to repeat a single task. So far, our loops have executed until they naturally reached the end. In the next article, we'll learn how to stop a loop early or skip specific iterations using the break and continue statements. I look forward to sharing it with you!
Top comments (0)