Lesson 3 of 5
Making Decisions with Conditionals
Letting Programs Choose
Real programs need to react differently to different situations. The if statement runs a block of code only when a condition is True.
marks = 75
if marks >= 50:
print("You passed!")Notice two things. The line ends with a colon, and the code that belongs to the if is indented (usually four spaces). In Python, indentation is not decoration — it defines which lines are inside the block.
Comparison Operators
==equal to (note: two equals signs)!=not equal to>greater than,<less than>=greater or equal,<=less or equal
else and elif
Use else for the fallback case, and elif (short for else if) to test more conditions in order.
marks = 82
if marks >= 80:
grade = "A+"
elif marks >= 70:
grade = "A"
elif marks >= 60:
grade = "A-"
else:
grade = "Needs improvement"
print(f"Your grade is {grade}")Python checks each branch from top to bottom and runs the first one that is True. The rest are skipped, so order matters.
Combining Conditions
The keywords and, or, and not let you build richer tests.
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
else:
print("Entry denied")and is True only when both sides are True. or is True when at least one side is True. not flips a value.
Common mistake: using a single=inside anif. A single equals sign assigns a value; a double==compares two values.
Discussion
0No comments yet — be the first to leave one!