Python for loop
In computer programming, a loop is a programming structure that repeats a sequence of instructions until a specific condition is met. Python has various types of loops, for loop is one of them. In this Python tutorial section, you will learn about for loop.
Objectives
-
Basic understanding of Python for loop
-
Else in Python For Loop
Basic understanding of Python for loop
Syntax
for value in sequence:
statement(s)
Code
# For loop
color_names = ["Red", "Green", "Blue", "Yellow"]
for name in color_names:
print(name)
Output
Red
Green
Blue
Yellow
Process finished with exit code 0
Above example you get list of colors, now you have to print them one after another. For solve the problem here used for loop where color_names
are color list in is keyword and name
is a variable where individual value come one after another by the for
. Under the for statement using print function to print the name of color.
Else in Python For Loop
The else keyword in a for
loop specifies a block of code to be executed when the loop is finished or some cases the loop not execute.
Syntax
for value in sequence:
statement(s)
else:
somethine else
Code
# For loop else execute when it's finish
color_names = ["Red", "Green", "Blue", "Yellow"]
for name in color_names:
print(name)
else:
print("Loop Completed")
print("\n ------ \n")
# For loop else execute when it has no item
color_names = []
for name in color_names:
print(name)
else:
print("Empty colors")
Output
Red
Green
Blue
Yellow
Loop Completed
------
Empty colors
Process finished with exit code 0