What is the difference between a for loop and a while loop in Python?
a) for loops are used for infinite loops, while loops are not
b) for loops iterate over a sequence, while loops run as long as a condition is true
c) for loops are faster than while loops
d) There is no difference
Answer:
b) for loops iterate over a sequence, while loops run as long as a condition is true
Explanation:
The primary difference between a for
loop and a while
loop in Python is in how they operate. A for
loop is typically used to iterate over a sequence (such as a list, tuple, or string), whereas a while
loop continues to execute as long as a specified condition remains true.
# Example of a for loop
for item in [1, 2, 3]:
print(item) # Iterates over each item in the list
# Example of a while loop
x = 0
while x < 3:
print(x)
x += 1 # Runs until x is no longer less than 3
A for
loop is ideal when you know the number of iterations in advance or when iterating over elements in a collection. A while
loop is better suited for scenarios where the number of iterations depends on a condition that may change during execution.
Understanding when to use each type of loop is essential for writing efficient and effective Python code.