Theory
Until now, our programs ran line by line. A conditional changes that flow: depending on a condition, the program chooses one of several paths.
Motivating example: absolute value
Given an integer x, print its absolute value. If x > 0, print x; otherwise print -x.
x = int(input())
if x > 0:
print(x)
else:
print(-x)
How it works:
ifis followed by a condition and a colon:.- The indented block under
ifruns when the condition is True. else:introduces the alternative block, which runs when the condition is False.
Syntax you’ll use
if CONDITION:
# Block 1
else:
# Block 2
Block 1 runs if CONDITION is true. Otherwise, Block 2 runs.
Single-branch (“incomplete”) if
You can omit else. Only the if block runs when the condition is true; the rest of the program continues regardless.
x = int(input())
if x < 0:
x = -x # change only when needed
print(x) # always runs
Multiple choices: if–elif–else
Use elif (“else if”) for more than two branches.
score = int(input("Score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(grade)
Indentation = block structure
- All lines belonging to the same block must have the same indentation.
- Recommended: 4 spaces per indentation level.
- Do not mix tabs and spaces (it can cause errors). Configure your editor to insert spaces on Tab.
Python vs other languages: Python uses indentation to mark blocks. Languages like C, C++, Java, and JavaScript use braces { ... }, while Pascal uses begin ... end and Ruby uses end.
Conditions & truthiness
- Common comparison operators:
==,!=,<,<=,>,>=. - Logical operators:
and,or,not. - “Falsy” values:
0,0.0,"",[],{},set(),None. Everything else is “truthy”.
name = input("Name (optional): ")
if name: # empty string is False
print("Hello,", name)
else:
print("Hello!")
Clean patterns
1) Guard clause (early exit)
def abs_val(x):
if x >= 0:
return x
return -x
<h3 style="margin:12px 0 6px; font-size:1.05rem;">2) Conditional expression (one-liner)</h3>
<pre style="background:#f6f8fa; padding:12px; border-radius:8px; overflow:auto;"><code class="language-python">x = int(input())
abs_x = x if x >= 0 else -x print(abs_x)
Common mistakes (and fixes)
- Forgetting the colon after
if/elif/else. - Inconsistent indentation (mixing tabs/spaces or misaligned blocks).
- Assignment vs comparison: use
==to compare, not=. - Unreachable code: placing code after a
returnin the same block.
Quick practice
- Read an integer and print
evenif it’s even, otherwiseodd. - Given two integers, print the larger one (no built-ins like
max). - Classify a number:
positive,negative, orzero.
Show sample solutions
# 1) even / odd
n = int(input())
if n % 2 == 0:
print("even")
else:
print("odd")
2) larger of two
a = int(input())
b = int(input())
if a >= b:
print(a)
else:
print(b)
3) sign
x = int(input())
if x > 0:
print("positive")
elif x < 0:
print("negative")
else:
print("zero")