
๐Python For & While Loops: Complete Guide with Examples
๐What is a Loop in Python?
Python For & While Loops: In Python, loops allow you to repeat a block of code multiple times until a specific condition is met. They are commonly used in programming to automate repetitive tasks.
๐What is a For Loop?
A For Loop is used to iterate over elements in a sequence, like a list or a range. It is ideal when you know the number of iterations required.
๐Python For & While Loops Example of For Loop:
python
for x in range(2, 7):
print(x)
๐Output:
2
3
4
5
6
๐In this example:
- The loop iterates through numbers from 2 to 6 (excluding 7).
- Each iteration prints the current number.
๐Python For & While Loops What is a While Loop?
A While Loop repeats a block of code as long as a specified condition is true.
๐Example of While Loop:
python
x = 0
while x < 4:
print(x)
x += 1
๐Output:
0
1
2
3
๐In this example:
- The loop starts with x = 0.
- The loop runs until x reaches 4.
- On each iteration, x is incremented by 1.
๐How to Use break in For Loop
The break statement is used to stop the loop before completion when a specific condition is met.
๐Example of Break Statement:
python
for x in range(10, 20):
if x == 15:
break
print(x)
๐Output:
10
11
12
13
14
๐In this example:
- The loop stops immediately when x == 15.
๐How to Use continue in For Loop
The continue statement is used to skip the current iteration and move to the next.
๐Example of Continue Statement:
python
for x in range(10, 20):
if x % 5 == 0:
continue
print(x)
๐Output:
11
12
13
14
16
17
18
19
๐In this example:
- Numbers divisible by 5 are skipped.
๐Using enumerate() in Python
The enumerate() function assigns an index to each item in an iterable, allowing you to track the position of elements while iterating.
๐Example of Enumerate Function:
python
Months = [“Jan”, “Feb”, “Mar”, “April”, “May”, “June”]
for i, m in enumerate(Months):
print(i, m)
๐Output:
0 Jan
1 Feb
2 Mar
3 April
4 May
5 June
๐In this example:
- i represents the index.
- m represents the month value.
๐Practical Example: Repeating the Same Statement
For repetitive tasks, a For Loop can efficiently repeat a statement.
๐Example:
python
for i in ‘123’:
print(“Software Moji Moji”, i)
๐Output:
nginx
Software Moji Moji 1
Software Moji Moji 2
Software Moji Moji 3
๐Python For & While Loops Key Takeaways
โ
Python has two primary types of loops: For Loop and While Loop.
โ
The break statement terminates a loop when a condition is met.
โ
The continue statement skips the current iteration and proceeds to the next.
โ
The enumerate() function provides an index for iterable elements.