Python / Core Python Fundamentals Interview Questions
How do conditional statements work in Python?
Python uses if, elif, and else to branch execution. Unlike many languages, Python relies on indentation (four spaces by convention) rather than braces to delimit blocks — mixing tabs and spaces causes a TabError.
score = 72 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' else: grade = 'F' print(grade) # C
Conditions are any expression that evaluates to a truthy or falsy value. Python considers 0, '', [], {}, None, and False as falsy; everything else is truthy. This means you can write if my_list: instead of if len(my_list) > 0:.
Python also supports a single-line ternary expression: result = 'pass' if score >= 70 else 'fail'. It reads left-to-right: value if condition else alternative. Overusing ternaries in complex conditions hurts readability, so reserve them for simple cases.
There is no switch statement prior to Python 3.10. From 3.10 onward, the match/case structural pattern matching statement fills that role and goes far beyond a simple value switch.
More Related questions...