Control Flow

Python Interview Questions for Control Flow: Easy Learn

Here are some interview questions on Python’s control flow methods, along with sample answers. These questions focus on if-else statements, loops (for and while), and control flow keywords (break, continue, pass).

Questions and Answers

Q1: Explain the difference between if, elif, and else in Python.

A1:

  • if: Checks a condition and executes the block of code under it if the condition is True.
  • elif: Stands for ‘else if’. It checks another condition if the previous if condition is False.
  • else: Executes a block of code if none of the previous conditions are True.
Python
if x > 10:
    print("x is greater than 10")
elif x == 10:
    print("x is equal to 10")
else:
    print("x is less than 10")

Q2: How does a while loop work in Python?

A2: A while loop executes a block of code as long as a condition is True.

Python
count = 0
while count < 5:
    print(count)
    count += 1

Q3: When would you use break and continue in a loop?

A3:

  • break: Exits the loop completely when a certain condition is met.
  • continue: Skips the remaining code in the current iteration and moves to the next iteration.
Python
for i in range(10):
    if i == 5:
        break
    print(i)
# Output: 0 1 2 3 4

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
# Output: 1 3 5 7 9

Q4: What does the pass keyword do?

A4: The pass keyword is a null operation. It serves as a placeholder where syntactically some code is required but where no action is desired or necessary.

Python
for i in range(3):
    if i == 1:
        pass
    else:
        print(f"Not passing on {i}")

Q5: What is the difference between a for loop and a while loop?

A5:

  • for loop: Iterates over a sequence (list, tuple, string, etc.) and executes a block of code for each item in the sequence.
  • while loop: Executes a block of code as long as a condition is True.
Python
# for loop
for i in [0, 1, 2]:
    print(i)
# Output: 0 1 2

# while loop
i = 0
while i < 3:
    print(i)
    i += 1
# Output: 0 1 2

I hope these questions and answers help you prepare for your Python interview!