Loops are an essential concept in programming that allows you to repeat a block of code multiple times. Python provides several loop structures and loop control statements that enable efficient iteration over data and performing repetitive tasks. This article explores the different types of loops in Python and covers loop control statements with code examples and explanations.
The for Loop
The for loop is commonly used to iterate over a sequence, such as a list, string, or range of numbers. It executes a set of statements for each item in the sequence.
Let’s see an example that iterates over list elements:
languages = ["C", "Dart", "Java", "Python", "Swift"]
# Iterating over languages
for language in languages:
# Print language to the console
print(language)
We have a list of languages, and the for loop iterates over each item in the list. The loop variable language takes on the value of each language in each iteration, and we print the language.
Let’s see another example that iterates over an open range of numbers 1 through 11:
# Iterating over an open range [1, 11)
for number in range(1, 11):
# Print number to the console
print(number)
We have an open range [1, 11), and the for loop iterates over each item in the range, excluding 11 because it is an open range. The loop variable number takes on the value of each number in each iteration, and we print the number.
By using the for loop, you can efficiently iterate over different types of sequences in Python.
While Loop
The while loop continues iterating until a given condition becomes false. It repeatedly executes a block of code as long as the condition is true.
Let’s see an example that prints numbers 1 through 10 using the while loop:
if __name__ == '__main__':
# Set counter initial value
count = 1
while count <= 10:
# Print current value of counter
print(count)
# Add 1 to counter
count += 1
The while loop continues until the count variable becomes greater than 10. It prints the current value of count in each iteration and increments it by 1 using the += operator.
Nested Loops
Nested loops are loops within loops. They allow you to perform iterations within iterations, enabling you to handle complex tasks.
Let’s see an example that prints the multiplication table using nested loops:
if __name__ == '__main__':
for i in range(1, 13):
for j in range(1, 13):
# End print with a tab, not newline
print(i * j, end="\t")
# Move to new line
print()
We have a nested for loop. The outer loop iterates over the numbers 1 to 12, and for each iteration, the inner loop also iterates over the numbers 1 to 12. Inside the inner loop, we calculate the product of the loop variables i and j using i * j and print the result. The end=”\t” parameter ensures that each print statement ends with a tab character, creating a multiplication table format. After completing the inner loop, we use the print() function without any arguments to move to a new line before starting the next iteration of the outer loop.
The else Clause on Loops
The for Loop
The for loop in Python can have an optional else clause, which is executed when the loop completes all iterations without encountering a break statement. It allows you to perform actions after the loop has finished executing.
Let’s see an example that demonstrates the else clause in a for loop:
if __name__ == '__main__':
languages = ["C", "Dart", "Java", "Python", "Swift"]
for language in languages:
print(language)
else:
print("No more languages!")
The for loop iterates over the list of languages. After printing each language, the loop completes all iterations. Since there is no break statement within the loop, the else clause is executed. It prints “No more languages!” to indicate that the loop has finished iterating over all the languages.
The while Loop
Similar to the for loop, the while loop in Python can also have an else clause. The else clause is executed when the condition of the while loop becomes false.
Let’s see an example that demonstrates the else clause in a while loop:
if __name__ == '__main__':
# Set counter initial value
count = 1
while count <= 10:
# Print the current value of counter
print(count)
# Add 1 to counter
count += 1
else:
print("Loop completed!")
The while loop continues until the count variable becomes greater than 10. After printing each value of count, the loop condition eventually becomes false. At this point, the else clause is executed, and it prints “Loop completed!” to indicate that the loop has finished executing.
The else clause on loops provides a convenient way to perform actions or provide feedback when a loop completes all iterations without encountering a break statement or when the loop condition becomes false in a while loop.
Loop Control Statements
Python provides loop control statements to modify the behavior of loops. The commonly used ones are break, continue, and pass.
The break Statement
It terminates the loop prematurely, bypassing the remaining iterations.
if __name__ == '__main__':
# A list of languages
languages = ["C", "Dart", "Java", "Python", "Swift"]
# Iterating over languages
for language in languages:
if language == "Python":
# Exit loop
break
# Print language to the console
print(language)
The for loop iterates over the list of languages. However, when it encounters the language “Python,” the break statement is executed, and the loop terminates. As a result, only “C”, “Dart” and “Java” are printed.
The continue Statement
It skips the rest of the code within the loop for the current iteration and moves on to the next iteration.
if __name__ == '__main__':
# A list of languages
languages = ["C", "Dart", "Java", "Python", "Swift"]
# Iterating over languages
for language in languages:
if language == "Python":
# Skip Python, Move to next iteration
continue
# Print language to the console
print(language)
The continue statement is used when the loop variable language is equal to “Python.” It skips the print statement for that iteration and moves on to the next language. As a result, “Python” is omitted from the output.
The pass Statement
It is used as a placeholder for code that will be implemented later. It acts as a no-op statement.
if __name__ == '__main__':
# A list of languages
languages = ["C", "Dart", "Java", "Python", "Swift"]
# Iterating over languages
for language in languages:
pass
The pass statement is placed inside the for loop, indicating that no additional code is required at this point. It allows the loop to iterate over the languages without executing any specific instructions.
Conclusion
Loops are an integral part of programming, and Python offers versatile loop structures and control statements to handle various looping scenarios. This article covered the for loop, while loop, nested loops, as well as loop control statements like break, continue, and pass. By mastering these concepts, you can efficiently iterate through data and solve repetitive tasks in Python.
Sources
I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!