Conditionals — if, elif, else
Write if/elif/else logic to categorise, flag and filter data in Python
Conditionals let your code make decisions — "if sales > 50000, mark as High; elif sales > 20000, mark as Medium; else mark as Low." In data analysis, this is how you create category columns, flag anomalies, and apply business rules to data.
Python uses indentation (4 spaces) instead of brackets to define code blocks. This is unlike most other languages and is the #1 syntax mistake beginners make.
Examples
Key Points
- ✓Indentation (4 spaces) defines code blocks — this is Python syntax, not style
- ✓and / or / not — Python uses words, not && || ! like other languages
- ✓For applying logic to DataFrame columns, use .apply() or np.select()
- ✓pd.cut() is the easiest way to bin numeric data into labelled ranges
- ✓Comparison operators: == (equal), != (not equal), >, <, >=, <=
Practice Question
What is the output of: label = "Pass" if 85 >= 60 else "Fail"?
Related Topics
Loops — for and whileIterate over data, automate repetitive tasks, and process multiple files with loopsFunctions in PythonWrite reusable functions to avoid repeating logic across your analysis scriptsFeature Engineering for AnalystsCreate new meaningful columns from existing data to improve analysis and modelling