Following are some sample interview questions and answers related to Python for-loops. These questions and answers aim to test understanding of basic to intermediate for loop concepts in Python.
Q1: What is a for loop in Python?
A1: A for-loop in Python is a control flow statement that iterates over a sequence (like a list, tuple, dictionary, or string). It executes a block of code for each item in the sequence.
for item in [1, 2, 3]:
print(item)
Q2: How do you iterate through a list using a for loop in Python?
A2: To iterate through a list in Python, you can use the for
keyword followed by a user-defined variable name, the in
keyword, and the list you want to iterate over. Here’s an example:
my_list = [1, 2, 3]
for item in my_list:
print(item)
Q3: How can you loop through a string character by character in Python?
A3: You can loop through a string character by character using a for-loop, similar to iterating through a list.
for char in "Hello":
print(char)
Q4: How do you use the range()
function in a for loop?
A4: The range()
function generates a sequence of numbers over which you can iterate using a for-loop. For example, to print numbers 0 to 4:
for i in range(5):
print(i)
Q5: What is the purpose of the break
statement in a for loop?
A5: The break
statement is used to exit the for-loop before it has gone through all the items in the sequence. It’s useful when you want to terminate the loop based on a certain condition.
for i in range(10):
if i == 5:
break
print(i)
Q6: What is a nested for loop? Provide an example.
A6: A nested for-loop is a for-loop within another for-loop. It allows you to iterate over multiple sequences, often used for 2D arrays or lists of lists.
for i in range(3):
for j in range(2):
print(f"(i, j) = ({i}, {j})")