if-else in Python — Python Technical Interview Questions & Answers
if-else in Python
if-else in Python
- if-else chooses a path. The computer looks at a condition. If it is True, it runs the if block. If not, it tries elif, then else. Only the first true branch runs. That is how Pass/Fail and even/odd work.
- Shape on the board: if n % 2 == 0: print("Even") else: print("Odd"). Colon after the condition. Body indented. Missing colon → SyntaxError. Wrong indent → IndentationError. = assigns; == compares. Freshers write if n = 2 and lose marks.
- Let’s dry-run. n = 7. 7 % 2 is 1, not 0, so if is False. else runs. Output: Odd. Change n to 8 → Even. Say that out loud before you run. That is the viva.
- elif is extra checks in order. marks >= 75 → A, elif >= 50 → B, else C. Don’t stack ten separate ifs when elif is the story.
- if-else in Python — output: Odd. 7 % 2 is 1, not 0. Change n to 8 → Even.
n % 2 == 0 ?
/ \
yes no
Even OddTechnical Interview Tip: Trace a pass/fail or even/odd example aloud.
Code Examples for if-else in Python
Example
# if-else
n = 7
if n % 2 == 0:
print("Even")
else:
print("Odd")
if-else in Python — output: Odd. 7 % 2 is 1, not 0. Change n to 8 → Even.
How to Explain if-else in Python to an Interviewer
Explain if-else as if you are teaching a junior — definition, then one tiny script.
If / elif / else First true wins
What does the example print, and why?
if-else in Python — output: Odd
What mistake do freshers make with if-else?
Needs colon + indent