Python If-Else: Conditions, Elif, Nested Ifs, and Ternary
Every day you make hundreds of decisions. If it's raining, you grab an umbrella. If the traffic light is red, you stop. If your phone battery is below 20%, you look for a charger. These are all conditional decisions — you check something and act based on the result.
Programs make decisions the same way. Without conditions, code would run the exact same way every single time — no matter what data it receives. Conditions let your programs respond to different situations, handle edge cases, and behave intelligently.
In this tutorial, you'll learn how Python makes decisions using if, else, and elif. By the end, you'll be writing programs that choose different paths based on user input, calculated values, and complex combinations of conditions.
How Does the Python if Statement Work?
The if statement is the simplest form of decision-making. It checks a condition. If the condition is True, the indented code below it runs. If the condition is False, Python skips that code entirely.
Notice the structure. The if keyword is followed by a condition (temperature > 30), then a colon (:). The lines below it are indented — that's how Python knows which code belongs inside the if block. The last line runs no matter what because it's not indented under the if.
Try changing the temperature to 25 in the code above and run it again. The two lines about heat will disappear, but you'll still see "Have a great day!" because it's outside the if block.
Adding else — What Happens When the Condition Is False?
An if statement alone can only do something or do nothing. But often you want to do one thing when the condition is true and a different thing when it's false. That's what else is for.
Think of if-else like a fork in the road. Python always goes one way or the other — never both, never neither. Exactly one block runs every time.
score = 85
if score >= 60:
print('You passed!')
if score < 60:
print('You failed.')score = 85
if score >= 60:
print('You passed!')
else:
print('You failed.')The version with else is better for two reasons. First, it's shorter and easier to read. Second, it's impossible to accidentally have both blocks run or neither block run. With two separate if statements, a typo in the second condition could cause bugs.
How Does elif Work for Multiple Conditions?
What if you have more than two options? Imagine grading a test: A, B, C, D, or F. You can't handle five outcomes with just if and else. That's where elif (short for "else if") comes in.
Python checks the conditions from top to bottom. The moment it finds one that's True, it runs that block and skips everything below it. If none of the conditions match, the else block runs as a safety net.
You can have as many elif blocks as you want. The else at the end is optional — but it's good practice to include it as a catch-all for unexpected values.
Nested If Statements — Conditions Inside Conditions
Sometimes you need to check a second condition only after a first one passes. For example, a theme park ride might first check your height, then check your age. You can put an if statement inside another if statement — this is called nesting.
The inner if only runs when the outer if is True. Notice how the indentation gets deeper — each level of nesting adds another layer of indentation.
if has_ticket:
if age >= 12:
if height >= 120:
print('Welcome!')if has_ticket and age >= 12 and height >= 120:
print('Welcome!')Python Ternary Operator — One-Line If-Else
Sometimes you have a simple if-else that just assigns a value. Python has a shortcut for this called the ternary operator (also called a conditional expression). It puts the entire if-else on one line.
The syntax is: value_if_true if condition else value_if_false. Read it like English: "status is 'adult' if age is at least 18, else 'minor'."
Common Mistakes with If-Else
Here are the most frequent bugs beginners make with conditional statements. Learn to recognize these patterns and you'll save yourself hours of debugging.
Practice Exercises
Time to practice! These exercises build from simple if statements to more complex conditional logic. Try each one before looking at hints.
Write a program that checks if a number is even or odd. A variable number is given with the value 7.
Print "even" if the number is even, or "odd" if it's odd.
Expected output:
oddHint: A number is even if number % 2 == 0 (the remainder when dividing by 2 is zero).
Write a program that gives clothing advice based on temperature. A variable temp is given with the value 22.
Rules:
"Wear shorts""Wear a t-shirt""Wear a jacket""Wear a coat"Expected output:
Wear a t-shirtWithout running the code, predict what it will print. Then run it to check.
Think carefully about which conditions are True and which are False.
This grade calculator has a bug. Every score gets the grade "D" even when it should be "A", "B", or "C". Fix the elif chain so it works correctly.
Expected output for score = 85:
Grade: BA movie theater charges $12 for adults (age 18 or over) and $8 for children (under 18). Use the ternary operator to set the price in one line, then print it.
A variable age is given with the value 14.
Expected output:
Ticket price: $8Write a login validator. Two variables are given: username and password.
Rules:
"admin" and password is "secret123", print "Welcome, admin!""admin" but password is wrong, print "Wrong password""User not found"Expected output for username = "admin", password = "wrong":
Wrong passwordSummary: Python If-Else Statements
| Here's everything you learned about Python conditionals: | ||
|---|---|---|
| --- | --- | --- |
if | if condition: | Run code when condition is True |
else | else: | Run code when if is False |
elif | elif condition: | Check additional conditions |
| Nested if | if inside if | Multi-level decisions |
| Ternary | x if cond else y | One-line if-else for simple values |
Key rules to remember:
if, elif, and else line ends with a colon (:)True condition== for comparison, not = (which is assignment)What's Next?
Now that you can make decisions, it's time to make your programs repeat things. In the next tutorial — [Python For Loops](/python/python-for-loops) — you'll learn how to loop through lists, ranges, and strings to process data without writing the same code over and over.