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
- How does Python know where an
ifblock ends?●From the indentation alone. Every line indented under the
ifby the same amount belongs to the block, and the first line back at theif's level ends it. PEP 8 uses four spaces per level. Mixing a tab and spaces in one block givesTabError: inconsistent use of tabs and spaces in indentation. - 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, sobool("0")isTrueandbool(" ")isTrue, whilebool(0)isFalse. - What is wrong with
if day == "Saturday" or "Sunday":?●●It is always true.
orjoins two operands,day == "Saturday"and the string"Sunday"on its own. Forday = "Monday", the left operand is False, soorreturns the right one, andday == "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 isTrueforday = "Sunday"(a tuple, Python 3.2). - What is the difference between a chain of
if/elifand a sequence of separateifstatements?●● - Why does the order of the conditions in an
elifchain matter?●● - What is the conditional expression, and when should you not use it?●
- What does
x = name or "Guest"do, and how does it differ fromx = name if name else "Guest"?●● - How can a condition avoid dividing by zero?●●
- When would you use
matchinstead ofif/elif?●● - What is the most common mistake with
match?●●
while loops
- When do you use
whilerather thanfor?● - How do you make sure a
whileloop terminates?● - Can a
whileloop's body run zero times? When exactly does the loop stop?●● - What is a sentinel value?●●
- What is the walrus operator, and what goes wrong without brackets?●●
for loops
- What is an iterable?●
- What does
rangereturn, and why islen(range(10**12))fast?●● - Why is
for i in range(len(items)):discouraged?●● - What does
zipdo when its arguments have different lengths?●● - After
for steps in week:finishes, doesstepsstill exist? Does assigning to the loop variable inside the body change the loop?●● - How many times does a nested loop's inner body run?●●
break, continue and else
- What is the difference between
break,continueandpass?● - Does
breakin a nested loop leave both loops?●● - When does a loop's
elseblock run?●● - When is
while True:withbreakthe right form?●●