What is a While Loop?
- A while loop executes a block of code as long as a specified condition is True.
Syntax:
while condition:
<statement>
Example:
i = 1
while i <= 5:
print(i)
i = i + 1
Output:
1
2
3
4
5
What is a For Loop?
- A for loop is used to execute a block of code repeatedly for a sequence of values.
Syntax:
range(start, stop, step)
Parameters:
start -> Starting value(included)
stop -> Ending value(not included)
step -> Increment or decrement value
Syntax:
for variable in sequence:
<statement>
Example:
for i in range(1,6):
print(i)
Output:
1
2
3
4
5
Difference between for loop and while loop:
For Loop:
Used when the number of iterations is known.
Iterates over a sequence.
Easier to use for fixed repetitions.
While Loop:
Used when the number of iterations is unknown.
Runs based on a condition.
Suitable for condition-based repetitions.
Top comments (0)