Junior — Middle
What is the difference between for and while loops in Python, and when is it better to use each?
sobes.tech AI
Answer from AI
In Python, the for loop is used to iterate over elements of iterable objects (lists, strings, ranges, etc.), while the while loop executes a block of code as long as the condition is true.
Differences:
- for is convenient when the number of iterations is known or the sequence to iterate over is known (e.g., elements of a list).
- while is suitable when the number of iterations is not known in advance and depends on a condition.
Example of for:
for i in range(5):
print(i)
It will output numbers from 0 to 4.
Example of while:
count = 0
while count < 5:
print(count)
count += 1
It also outputs numbers from 0 to 4, but the loop continues as long as the condition count < 5 is true.
The choice depends on the task: if you need to iterate over elements, for is better; if you need to repeat actions until a condition is met — while.