The for loop in Python is one of the main looping constructs. Usually we use the for loop when we want to iterate over the sequence.
This sequence could be a collection, such as tuple, list, or even a string.
As a result of iteration, the placeholder variable takes every item as we iterate over the sequence.
In the case of the ‘for loop’ statement, once the initialization expression initializes the loop (int i = 0), it starts executing once, as the loop begins.
That is why the output of ‘for loop’ starts with 0, and the output of ‘while loop’ starts with 1.
names = ['John', 'Json', 'Emily', 'Catty', 'James']
for name in names:
print(f"Name: {name}")
# output
Name: John
Name: Json
Name: Emily
Name: Catty
Name: James
We can control the flow of the logic using the if-else block inside the for loop in Python.
On that account, we can stop the iteration at some point.
We can use the continue or break keywords to control the pace of the iteration.
numerical_values = range(10)
for numerical_value in numerical_values:
'''
if value equals 4, don't print but continue iteration
'''
if numerical_value == 4:
continue
else:
print(numerical_value, end=' ')
# output
0 1 2 3 5 6 7 8 9
The above code points out the same logic that we are trying to say.
We have a range of numbers up to 10.
Since the for loop starts its iteration from 0, it will end at 9.
However, according to our logic, we have omitted the number 4.
Hence the output doesn’t include 4.
Let’s try it different way.
numerical_values = range(10)
for numerical_value in numerical_values:
'''
if value equals 4, don't print anymore and stop iteration
'''
if numerical_value == 4:
break
else:
print(numerical_value, end=' ')
# output
0 1 2 3
It shows that we have come out of the loop when the iteration meets the number 4.
Besides this, in Python, we can use the else block with the for loop.
numerical_values = range(6)
for numerical_value in numerical_values:
print(numerical_value)
else:
print('We are out of loop.')
# output
0
1
2
3
4
5
We are out of loop.
Incidentally, we use the for loop for solving many problems in Python.
If you are a programming beginner you may take an interest in the following posts.
Steps in program development
Learn Programming Techniques
The levels of programming languages
What is high level language?
What is language portability?
Programming languages translators
Learn structured programming
Machine language to Assembly language
In fact, the looping construct and the if-else block together are indispensable in every kind of algorithm we see around us.
For example, while iterating over the sequence of numerical values, we can add them up.
start = 1
end = 5
sum = 0
for i in range(start, end + 1):
print(i, end=' ')
sum += i
if i==5:
break
print(f'= {sum}')
# output
1 2 3 4 5 = 15
For more Python code, please visit the respective GitHub Repository.
What Next?
TensorFlow, Machine Learning, AI and Data Science
Leave a Reply