The for loop in Python allows the programmer to repeat a block of code indefinitely, or until some conditions change. The for loop can be used with other Python control flow statements, such as if and while loops. This article will discuss the basics of how to use the for loop in Python programming examples, including code snippets and explanations of their function. I highly recommend you get the “Python Crash Course Book” to learn Python.
Example 1: Print List Elements using For Loop
subjects = ['AI','ML','DL','DS'] for x in subjects: print(x)
Output:
AI ML DL DS
Example 2: For Loop on String
for n in "AiHints": print(n)
Output:
A i H i n t s
Example 3: For Loop Range
for n in range(7): print(n)
Output:
0 1 2 3 4 5 6
Example 4: For Loop Range (Initial and Final Position)
for n in range(15, 20): print(n)
Output:
15 16 17 18 19
Example 5: For Loop Range with Step Size
for n in range(15, 30, 3): print(n)
Output:
15 18 21 24 27
Example 6: Create Table using For Loop
n = 2 for x in range(1, 11): print(n, "*", x, "=", x * n)
Output:
2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 2 * 10 = 20
Example 7: For Loop Break Statement
subjects = ['AI','ML','DL','DS'] for x in subjects: print(x) if x == 'DL': break
Output:
AI ML DL
Example 8: For Loop Break
subjects = ['AI','ML','DL','DS'] for x in subjects: if x == 'DL': break print(x)
Output:
AI ML
Example 9: For Loop Continue Statement
subjects = ['AI','ML','DL','DS'] for x in subjects: if x == 'DL': continue print(x)
Output:
AI ML DS
Example 10: Nested For Loops Python
colors = ['blue', 'orange', 'red'] objects = ['table', 'chair', 'fan'] for i in colors: for j in objects: print(i, j)
Output:
blue table blue chair blue fan orange table orange chair orange fan red table red chair red fan