🔍 Quick Lesson
Selection in Python allows your programs to make decisions and execute certain code only when specific conditions are met. This is achieved using conditional statements like if
, elif
, and else
.
What is Selection?
Selection, also known as conditional execution, enables a program to choose different paths based on certain conditions. This is fundamental in programming, allowing your software to respond intelligently to inputs and situations.
The if
Statement
The simplest form of selection is the if
statement. It executes a block of code only if a specified condition is True
.
age = 18
if age >= 18:
print("You are an adult.")
Here, the message will be printed only if age
is 18 or more.
The else
Clause
An else
clause can be added to handle what happens when the condition is not met.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The elif
Clause
The elif
(short for "else if") clause allows checking multiple conditions sequentially.
grade = 85
if grade >= 90:
print("Grade: A")
elif grade >= 80:
print("Grade: B")
elif grade >= 70:
print("Grade: C")
else:
print("Grade: F")
This evaluates from top to bottom and stops at the first true condition.
Comparison Operators
Comparison operators are used to form conditions. Common operators include:
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
Logical Operators
Combine multiple conditions using logical operators:
and
: True if both conditions are trueor
: True if at least one condition is truenot
: Inverts the truth value
age = 25
if age > 18 and age < 65:
print("You are of working age.")
Nested Conditions
You can nest if
statements inside each other for more complex logic.
score = 95
if score >= 60:
if score >= 90:
print("Excellent!")
else:
print("Passed.")
else:
print("Failed.")
Best Practices
- Use indentation correctly – Python uses it to define blocks.
- Keep conditions readable and avoid excessive nesting when possible.
- Use boolean variables to clarify intent in complex conditions.