Python Loop Exp
Python Loop Exp
Output:
nginx
CopyEdit
apple
banana
cherry
Output:
0
1
2
3
4
Output:
0
1
2
3
4
4. Loop with break (Stopping Early):
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
Output:
0
1
2
4
6. Nested Loops:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
The for loop with the range() function is commonly used in Python to iterate over a sequence of
numbers. Here's a detailed explanation:
Syntax of range()
The range() function generates a sequence of numbers, which is then iterated over by the for
loop. It can take one, two, or three arguments:
1. range(stop)
Generates numbers from 0 up to (but not including) stop.
2. range(start, stop)
Generates numbers from start up to (but not including) stop.
3. range(start, stop, step)
Generates numbers from start to stop, incrementing by step.
Examples
for i in range(5):
print(i)
Explanation:
Output:
0
1
2
3
4
Explanation:
Output:
2
3
4
5
3. Using step (range(start, stop, step)):
Explanation:
Output:
0
2
4
6
8
Explanation:
Output:
5
4
3
2
1
Key Points
0
1
2
3
4
5
6
7
8
9
Output:
1
2
3
4
5
Output:
0
2
4
6
8
10
10
9
8
7
6
5
4
3
2
1
Output:
Sum: 55
Output:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Output:
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
8. Nested Loops Example
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
Output:
1
3
5
7
9
Output:
Character at index 0 is H
Character at index 1 is e
Character at index 2 is l
Character at index 3 is l
Character at index 4 is o