As Python has many iterate-able objects, we can grab the values of objects one by one. We can print sequentially from either a list, a tuple, a dictionary, a set, or a string.
A “for loop” in Python is used to iterate over a sequence (such as a list, tuple, string, or dictionary) and execute a block of code for each item in the sequence. It follows a specific syntax:
We will use the “for” keyword for this loop.
for item in sequence:
# Code block to execute for each item
PythonHere, “item” represents the variable that takes each value from the sequence iteratively, and “sequence” refers to the iterable object being looped through. The code block beneath the loop is executed once for each item in the sequence.
Example
colors = {"red", "yellow", "orange"}
for x in colors:
print(x)
PythonOutput red yellow orange |
Looping through a String
We can apply for loop on a string to print all the string’s characters individually.
for x in "Banana":
print(x)
PythonOutput B a n a n a |
Break Statement
Using the break statement, we can stop loop statements to print at a specific point even if our condition is true.
Example
colors = ["red", "yellow", "orange"]
for x in colors:
print(colors)
if x == "yellow":
break
PythonOutput [‘red’, ‘yellow’, ‘orange’] [‘red’, ‘yellow’, ‘orange’] |
Continue Statement
We can stop current statements to print and continue with the next statements by using the continue statement:
Example
colors = ["red", "yellow", "orange"]
for x in colors:
if x == "yellow":
continue
print(colors)
PythonOutput [‘red’, ‘yellow’, ‘orange’] [‘red’, ‘yellow’, ‘orange’] |
Else in For Loop
If the given condition is not true, we can print an else statement.
for x in range(3):
print(x)
else:
print("Finally finished!")
PythonOutput 0 1 2 Finally finished! |
Nested If using Python for loop
We can use for statements inside for statements, this is called nested for statements.
colors = ["red", "yellow"]
numbers = [1, 2]
for x in colors:
for y in numbers:
print(x, y)
PythonOutput red 1 red 2 yellow 1 yellow 2 |
Pass Statement
We cannot use if statement empty, if you have to use if condition without any statement, we have to use pass keyword:
for x in [0, 1, 2]:
pass
print("Loop completed")
PythonOutput Loop completed. The output will be the empty for loop. |
Author: TCF Editorial
Copyright The Cloudflare.
Related Topics