SchoolWhool
Quizzes and saved progress, freeSign in freeSign in
Python · Module 2Module material

Python loops and conditions interview questions

25 questions interviewers ask on control flow, from first principles to the follow-ups. The first 3 model answers are free to read; Pro opens the rest.

Conditions

  1. How does Python know where an if block ends?●

    From the indentation alone. Every line indented under the if by the same amount belongs to the block, and the first line back at the if's level ends it. PEP 8 uses four spaces per level. Mixing a tab and spaces in one block gives TabError: inconsistent use of tabs and spaces in indentation.

  2. Which values are falsy in Python?●

    False, None, zero of any number type (0, 0.0), and empty strings and collections ("", and the empty list, tuple, set and dictionary from Module 3). Everything else is truthy, so bool("0") is True and bool(" ") is True, while bool(0) is False.

  3. What is wrong with if day == "Saturday" or "Sunday":?●●

    It is always true. or joins two operands, day == "Saturday" and the string "Sunday" on its own. For day = "Monday", the left operand is False, so or returns the right one, and day == "Saturday" or "Sunday" is 'Sunday', a non-empty string. Write the name in each comparison, day == "Saturday" or day == "Sunday", or test membership, day in ("Saturday", "Sunday"), which is True for day = "Sunday" (a tuple, Python 3.2).

  4. What is the difference between a chain of if/elif and a sequence of separate if statements?●●
  5. Why does the order of the conditions in an elif chain matter?●●
  6. What is the conditional expression, and when should you not use it?●
  7. What does x = name or "Guest" do, and how does it differ from x = name if name else "Guest"?●●
  8. How can a condition avoid dividing by zero?●●
  9. When would you use match instead of if/elif?●●
  10. What is the most common mistake with match?●●

while loops

  1. When do you use while rather than for?●
  2. How do you make sure a while loop terminates?●
  3. Can a while loop's body run zero times? When exactly does the loop stop?●●
  4. What is a sentinel value?●●
  5. What is the walrus operator, and what goes wrong without brackets?●●

for loops

  1. What is an iterable?●
  2. What does range return, and why is len(range(10**12)) fast?●●
  3. Why is for i in range(len(items)): discouraged?●●
  4. What does zip do when its arguments have different lengths?●●
  5. After for steps in week: finishes, does steps still exist? Does assigning to the loop variable inside the body change the loop?●●
  6. How many times does a nested loop's inner body run?●●

break, continue and else

  1. What is the difference between break, continue and pass?●
  2. Does break in a nested loop leave both loops?●●
  3. When does a loop's else block run?●●
  4. When is while True: with break the right form?●●