
Making Smart Decisions: Python Conditional Statements Mastered
You now know how to store information in variables. But real programs need to react to that information. They approve a login, calculate a discount, or flag an error. That's exactly what Python if else statements (also called conditional statements) let you do. They make your program think and decide, just like humans do every day.
The Basic If Statement
An if statement runs a block of code only when a condition is true:
temperature = 15
if temperature < 18:
print("It's a chilly night in Ruteng, grab a jacket!")
Notice two things here. The line ends with a colon (:), and the next line is indented. Python uses that indentation, 4 spaces, to know exactly which lines belong inside the if block. If you skip the colon or the indentation, Python will raise a SyntaxError or IndentationError right away.
Comparison Operators
These operators compare two values and always produce a boolean result, True or False:
==equal to!=not equal to>greater than<less than>=greater than or equal to<=less than or equal to
A common beginner mistake is writing = instead of == inside a condition. Remember, one equals sign assigns a value. Two equals signs compare two values.
Else and Elif: Handling Multiple Possibilities
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Your grade is {grade}")
elif is short for “else if”. It lets you check several conditions in order. Python checks each one from top to bottom and runs the first block that matches. As soon as one condition is true, Python skips every condition below it. else catches everything that didn't match any condition above it.
This top to bottom order matters a lot. In the example above, if you tried score = 95 against a chain that started with elif score >= 80 before elif score >= 90, the score would wrongly get a B, because Python stops at the first true condition it finds. Always put the more specific or higher condition first.
Logical Operators: and, or, not
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry approved.")
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No work today!")
if not has_id:
print("Please bring identification.")
You can combine multiple conditions with three keywords. and needs both sides to be true. or only needs one side to be true. not flips a boolean, turning True into False and the other way around. Python reads these left to right, so age >= 18 and has_id first checks the age, then checks the ID, and both need to pass.
Nested Conditionals
weather = "rainy"
has_umbrella = False
if weather == "rainy":
if has_umbrella:
print("Go ahead, you're covered!")
else:
print("Better wait it out or grab an umbrella first.")
else:
print("Enjoy the nice weather!")
Putting a conditional inside another conditional is called nesting. Each level of nesting adds one more layer of indentation. It's a useful tool, but too much nesting makes code hard to read. In this case, you could also write it with and: if weather == "rainy" and has_umbrella:. Combining conditions with and or or is often cleaner than nesting several if blocks inside each other.
Understanding Truthiness in Python
Python doesn't only check for True or False in an if statement. It also accepts other values and treats them as “truthy” or “falsy”. These values are automatically treated as False: the number 0, an empty string "", None, and an empty list or dictionary. Every other value is treated as True.
user_input = ""
if user_input:
print("You typed something.")
else:
print("Input field was empty.")
This pattern is common in real Python code. Instead of writing if user_input != "":, most Python developers simply write if user_input:, letting the empty string's natural falsiness do the work.
A Shortcut: The Conditional Expression
For simple cases, Python offers a compact one line version of if/else, often called a ternary expression. It's worth knowing, even though the full if/else is still more common for anything complex:
age = 16
status = "adult" if age >= 18 else "minor"
print(status) # "minor"
Read it in this order: the value if true, then the condition, then the value if false. This line does exactly the same thing as a four line if/else block, just in one line.
Practical Project: Grade Calculator
name = input("Student name: ")
score = float(input("Enter numerical score: "))
if score >= 90:
grade = "A"
comment = "Outstanding work!"
elif score >= 80:
grade = "B"
comment = "Great job!"
elif score >= 70:
grade = "C"
comment = "Good effort, keep practicing."
elif score >= 60:
grade = "D"
comment = "You passed, but review the material."
else:
grade = "F"
comment = "Let's schedule some extra study time."
print(f"n{name}'s Grade Report")
print(f"Score: {score} | Grade: {grade}")
print(f"Comment: {comment}")
Two details are easy to miss here. First, score = float(input(...)) converts the text from input() into a number right away, so comparisons like score >= 90 actually work. Without that conversion, Python would try to compare a string to a number and crash with a TypeError. Second, notice that both grade and comment are set together inside each branch. This keeps related information grouped in one place, so the print statements at the end stay simple and don't need any if logic of their own.
Debugging Decision Logic
- Wrong operator: using
=instead of==inside a condition causes aSyntaxError. Python won't let you assign a value by accident inside an if statement. - Order matters with elif: Python checks conditions top to bottom and stops at the first match. Put more specific or higher conditions first, as shown in the grading example above.
- Comparing different types: comparing a string to a number, like
"10" > 5, raises aTypeError. Make sure both sides of a comparison use the same type, converting withint()orfloat()if needed. - Forgetting the colon: every
if,elif, andelseline must end with a colon, even when the condition looks complete without one.
Try It Yourself
Practice these three short exercises in a new file called practice_conditions.py before moving on:
- Write a program that asks for a number and prints whether it is positive, negative, or zero.
- Write a program that asks for someone's age and, using
and, checks whether they are old enough to vote (18 or older) and hold an Indonesian ID at the same time. - Rewrite the grade calculator's first branch,
if score >= 90, as a one line conditional expression that sets a variable calledpassed_with_honorstoTrueorFalse.
Frequently Asked Questions
Can I use if statements without an else?
Yes, an else block is completely optional. Use a standalone if whenever you only need to react to one specific condition and do nothing otherwise.
How many elif statements can I chain together?
There's no hard limit. But if you find yourself writing more than 4 or 5 elif blocks, consider whether a dictionary lookup or a function might be cleaner. We'll cover both ideas in later articles.
What's the difference between and and &&?
Python uses the plain English word and, not the symbol && found in languages like JavaScript or C. Using && in Python raises a SyntaxError.
Why does my elif never run?
This usually means an earlier condition in the chain is already catching cases meant for a later one. Double check the order and the boundaries of your comparisons, from top to bottom.
Is 0 always treated as False?
Yes, in a boolean context like an if statement, the integer 0 and the float 0.0 are both treated as False. Any other number, including negative numbers, is treated as True.
Ready to automate repetitive tasks and process large datasets? In our next article, we'll explore Python loops. You'll learn how to combine conditional logic with repeated actions to build programs that handle data automatically. We'll build a project that shows why automation is one of programming's most valuable skills.
Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you run into confusion while working through these conditional statement concepts, get stuck on a specific logical scenario, or discover an interesting variation on the grade calculator project, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each other's discoveries and solutions.
You Might Also Like

Handling Errors Like a Professional Python Developer
... Read more

Writing Clean Python Functions: Code Organization Made Simple
... Read more

Python Dictionaries: Storing Data with Purpose
Master Python dictionaries — key-value pairs, nesting, and comprehensions — with a hands-o...

Python Lists: Your First Data Structure Adventure
Master Python lists — creation, indexing, slicing, methods, and comprehensions — with a ha...
Comments
No comments yet — be the first to start the conversation!