For Loop in Python with Examples

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

Python

Output:

AI
ML
DL
DS

Example 2: For Loop on String

Python

Output:

A
i
H
i
n
t
s

Example 3: For Loop Range

Python

Output:

0
1
2
3
4
5
6

Example 4: For Loop Range (Initial and Final Position)

Python

Output:

15
16
17
18
19

Example 5: For Loop Range with Step Size

Python

Output:

15
18
21
24
27

Example 6: Create Table using For Loop

Python

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

Python

Output:

AI
ML
DL

Example 8: For Loop Break

Python

Output:

AI
ML

Example 9: For Loop Continue Statement

Python

Output:

AI
ML
DS

Example 10: Nested For Loops Python

Python

Output:

blue table
blue chair
blue fan
orange table
orange chair
orange fan
red table
red chair
red fan

Leave a Comment

Your email address will not be published.