Intern
199
What is the difference between a while loop and a for loop?
Answer from AI
sobes.tech AI
| Aspect | while loop |
for loop |
|---|---|---|
| Usage | Iterates until the condition is met. | Iterates over elements of a sequence. |
| Condition | Explicitly specified, checked before each iteration. | Iterates over elements of an iterable object (list, string, tuple, etc.). |
| Number of iterations | Unknown in advance, depends on the condition. | Known in advance, equal to the number of elements in the sequence. |
| Initialization and increment | Must be explicitly implemented (outside and inside the loop). | Occur automatically for each element of the sequence. |
# Example of a while loop
count = 0
while count < 5:
print(count)
count += 1 # Manual increment
# Example of a for loop
items = [1, 2, 3, 4, 5]
for item in items: # Iteration over list elements
print(item)