Conditional Statements
Conditional statements allow a program to make decisions and execute different blocks of code depending on whether a condition is true or false. This is what gives your programs the ability to respond intelligently to different situations and data.
The if, elif, and else Statements
score = 78
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
print(grade) # Output: B
In the example above, Python checks each condition in order and executes the first block whose condition evaluates to true, skipping the rest.
Why This Matters in Data Science
- Filtering datasets based on specific criteria
- Flagging outliers or missing values during data cleaning
- Building rule-based logic before applying machine learning models
Next Up
Conditions decide what happens once. To repeat actions across data, you need loops, the focus of the next topic.