Q1. What are the types of loops in Python?
Python provides two loop constructs: for loop (iterates over a sequence) and while loop (repeats while condition is true). Example:
for i in range(5): print(i)
while x < 10: x += 1Q2. How does the for loop work in Python?
The for loop iterates over items of any sequence (list, string, tuple, dictionary, etc.) or any iterable. Example:
for item in [1,2,3]: print(item) It uses the iterator protocol.Q3. How do you use the range() function?
range() generates a sequence of numbers. Common uses:
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) It is lazy, producing numbers on demand.Q4. How do you iterate over both index and value?
Use enumerate() function. Example:
for idx, val in enumerate([''a'',''b'',''c'']):
print(idx, val)Q5. What is an infinite loop and how to avoid it?
An infinite loop occurs when the loop condition never becomes false. In while loops, ensure the condition changes. In for loops, it's harder to create infinite loops. Use break to exit early if needed. Example of infinite while: while True: ... (must have break inside).
