Python if, elif & else StatementsGet Certified
What Is a Conditional Statement?
A conditional statement lets a program make decisions. Instead of running every line from top to bottom, the program checks a condition and chooses which block of code to run. Real programs do this all the time: they show a different message to a logged-in user, give a discount only above a certain amount, or print a warning when a value is too high. In Python, decisions are written with the keywords if, elif (short for “else if”), and else.
if: runs a block of code only when a condition is true.else: runs a block when theifcondition is false.elif: checks another condition when the earlier ones were false.- Conditions: expressions that give
TrueorFalse, built with comparison and logical operators. - Indentation: the indented lines under a colon form the block that belongs to the condition.
- Truthiness: any value can be used as a condition. Empty and zero values count as false.
The if Statement
An if statement has three parts: the keyword if, a condition, and a colon :. The lines that should run when the condition is true come next and must be indented, usually by four spaces. When the condition is false, Python skips the indented block and continues with the first line that is not indented. A condition is any expression that evaluates to True or False. The most common conditions use these comparison operators:
==equal to, and!=not equal to.>greater than, and<less than.>=greater than or equal to, and<=less than or equal to.
Remember that a single = assigns a value to a variable, while a double == compares two values.
Try It: A Simple if
Click Test My Code. Then change temperature to 20 and run it again to see which line disappears.
temperature = 31
if temperature > 30:
print("It is hot today")
print("This line always runs")temperature refers to the integer 31.temperature > 30 compares the two numbers. Because 31 is greater than 30, the condition is True. The colon at the end opens a block.if. It runs only when the condition is true. The output is It is hot today.if block and always runs. The output is This line always runs.The else Clause
Add an else clause when you want something to happen if the condition is not true. The else keyword has no condition of its own. It is followed directly by a colon and an indented block. Exactly one of the two blocks runs: never both and never neither. A classic use is to test whether a number is even or odd with the remainder operator %, because an even number leaves a remainder of 0 when divided by 2.
Try It: if and else
Click Test My Code. Change number to 10 and run it again.
number divided by 2 is zero. If it is, the program reports that the number is even. Otherwise it reports that the number is odd.number = 7
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")number refers to the integer 7.7 % 2 is 1, which is not equal to 0, so the condition is False and Python jumps to the else block.else: has no condition. It catches every case in which the if condition was false.7 is odd.Several Choices with elif
When there are more than two possibilities, add one or more elif branches between if and else. Python checks the conditions from top to bottom and runs the block of the first condition that is true. After that block finishes, the rest of the chain is skipped. This is why the order matters: put the most specific or highest condition first. The final else is optional and acts as a safety net when nothing else matched.
Python has no separate else if keyword. The word is always spelled elif.
Try It: A Grade Calculator
Click Test My Code. Try the scores 95, 60, and 30 and watch which branch runs.
score = 76
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(f"Score {score}: grade {grade}")score refers to the integer 76.76 >= 90 first. It is False, so the next branch is tried.76 >= 75 is True, so Python runs this branch and skips the rest of the chain.grade is set to "B".score >= 60 is never tested, because an earlier branch already matched. Every score of 75 or more would reach the earlier branch first, which is why the limits are listed from high to low.else would handle every score below 60. It is skipped here.Score 76: grade B.Logical Operators and Combined Conditions
The logical operators and, or, and not combine conditions into larger ones.
a and bis true only when both parts are true.a or bis true when at least one part is true.not areverses the value: true becomes false and false becomes true.
Python also allows chained comparisons, so 18 <= age < 65 means “age is at least 18 and less than 65”. The operators and and or use short-circuit evaluation: Python stops as soon as the answer is known, so in a and b it never looks at b when a is already false. For identity tests use is and is not, mainly with None. For ordinary values use ==.
Try It: Combining Conditions
Click Test My Code. Change has_ticket to False and predict which lines change.
or, not, and and. It then shows which values Python treats as false, and tests values against None.age = 25
has_ticket = True
print(18 <= age < 65)
print(age > 30 or has_ticket)
print(not has_ticket)
print(age >= 18 and has_ticket)
print(bool(0), bool(""), bool([]), bool("False"))
print(None is None, 5 is not None)age refers to the integer 25.has_ticket refers to True.18 <= age < 65 checks both limits at once. 25 is in that range, so the output is True.age > 30 is false, but has_ticket is true. Only one side needs to be true for or, so the output is True.not reverses True, so the output is False.True.bool() shows how Python treats a value as a condition. Zero, an empty string, and an empty list are false. A non-empty string is true, even when its text is "False". The output is False False False True.None is None is True, and the number 5 is not None, so 5 is not None is also True. The output is True True.Truthiness and Membership in Conditions
A condition does not have to be a comparison. Python treats these values as false: False, None, the number zero (0, 0.0), and empty collections such as "", [], (), {}, and set(). Almost everything else is true. This allows short, readable checks such as if items: instead of if len(items) > 0:. The in and not in operators test whether a value is inside a string, list, or other collection, and they are very common in conditions.
Try It: Truthy and Falsy Values
Click Test My Code. Change items to an empty list [] and see what happens to the second message.
in and a test with not in.name = ""
items = [3, 5]
if not name:
print("Name is empty")
if items:
print("Items:", len(items))
if 5 in items and "x" not in "python":
print("Both tests passed")name refers to an empty string, which counts as false.items refers to a list with two numbers. A non-empty list counts as true.not name is True, because an empty string is false and not reverses it.Name is empty.if items: is true when the list has at least one item.Items: 2.5 in items is true because 5 is in the list. "x" not in "python" is true because the word has no letter x. Both sides of and are true.Both tests passed.Nested if Statements
An if statement can be placed inside another one. This is called nesting, and each level is indented by four more spaces. Nesting is useful when a second question only makes sense after the first one is answered. Deeply nested code quickly becomes hard to read, so combine conditions with and or use elif whenever that is clearer.
Try It: Ticket Prices
Click Test My Code. Change age to 40 and then to 70 to visit the other branches.
if. Adults and seniors are handled by an elif and an else.age = 15
is_student = True
if age < 18:
if is_student:
price = 5
else:
price = 8
elif age < 65:
price = 12
else:
price = 6
print("Ticket price:", price)age refers to the integer 15.is_student refers to True.15 < 18 is True, so Python enters this block and ignores the elif and else that follow.if is indented one level deeper. It is checked only because the outer condition was true. is_student is True.5.else lines up with the inner if, so it belongs to it and not to the outer one.elif lines up with the outer if. It is skipped here because the first branch already ran.else handles ages of 65 and over. It is skipped here.Ticket price: 5.Conditional Expressions and Shortcuts
For a simple choice between two values, Python offers a one-line conditional expression, also called the ternary operator: value_if_true if condition else value_if_false. It is an expression, so you can assign it to a variable or use it inside an f-string. You can chain two of them for three choices, but a regular if / elif / else block is easier to read when there are many branches. Another popular shortcut is the or operator, which returns its first value when that value is truthy and its second value otherwise. It is often used to provide a default.
Try It: One-Line Decisions
Click Test My Code. Change temp to 30 to reach the last choice.
or to replace an empty nickname with a default.n = 8
parity = "even" if n % 2 == 0 else "odd"
print(parity)
temp = 5
label = "cold" if temp < 10 else "warm" if temp < 25 else "hot"
print(label)
nickname = ""
print(nickname or "Guest")n refers to the integer 8.8 % 2 == 0 is true, the first value "even" is chosen and stored in parity.even.temp refers to the integer 5.temp < 10. It is true, so the result is "cold". The rest of the expression is not evaluated.cold.nickname refers to an empty string, which is false.or is false, Python returns the right side. The output is Guest.Tip: Write the most likely or most important case first, keep each branch short, and give variables clear names such asis_studentorhas_ticket. A condition that reads like an English sentence is easier to understand and to debug.
Using if with User Input
Conditions become more powerful when they respond to the information entered by a user. Remember that input() always returns a string, so convert the value with int() or float() before comparing it with a number. You can also use strip() to remove extra spaces and lower() to convert text to lowercase. This helps make different versions of an answer, such as Yes, yes, and YES , match correctly. By combining user input with conditional statements, you can create programs that respond to different answers.
Try It: Positive, Negative or Zero
The Program Input box is already filled with -4. Click Run Code straight away, then try 0 and 7.
if / elif / else chain to report whether it is positive, negative, or zero. A second, separate if / else then reports whether it is even or odd.number = int(input("Enter a whole number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
if number % 2 == 0:
print("Even")
else:
print("Odd")input() reads the text -4, and int() converts it to the integer -4.-4 > 0 is False, so Python moves on.-4 < 0 is True, so this branch runs.Negative.else would run only for zero. It is skipped here.if is not indented, so it starts a new decision. The first chain is finished. -4 % 2 is 0, so the condition is true.Even.else belongs to the second if. It is skipped here.Try It: A Leap Year Checker
The Program Input box is filled with 2024. Click Run Code, then try 1900, 2000, and 2026.
year = int(input("Enter a year: "))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")input() reads 2024 and int() converts it to a number.2024 % 400 is not 0, so the left side of or is false. On the right side, 2024 % 4 == 0 is true and 2024 % 100 != 0 is true, so the parenthesized part is true. The whole condition is True. The parentheses make the grouping clear.2024 is a leap year.else handles every year that failed the rule, such as 1900 or 2026.2026 it would print 2026 is not a leap year.Try It: A Discount Calculator
The Program Input box is filled with two lines: 120 and yes. Click Run Code, then change the amount to 80 or the answer to no.
if / elif chain that combines conditions with and, then calculates and prints the discount and the final price.amount = float(input("Purchase amount: "))
member = input("Are you a member (yes/no)? ").strip().lower()
if amount >= 100 and member == "yes":
discount = 0.20
elif amount >= 100:
discount = 0.10
elif member == "yes":
discount = 0.05
else:
discount = 0
final = amount * (1 - discount)
print(f"Discount: {discount:.0%}")
print(f"You pay: {final:.2f}")120, converted to the float 120.0.input() reads the text, strip() removes outer spaces, and lower() makes it lowercase, so Yes, YES , and yes all become yes.and must be true. The amount is at least 100 and the person is a member, so this branch runs. The most specific case is listed first on purpose.0.20.else would handle everyone else. It is skipped here.1 - discount is the share of the price that is still paid. 120 times 0.8 is 96.:.0% turns the fraction into a whole percentage. The output is Discount: 20%.You pay: 96.00.Common Mistakes with Conditions
- Using
=instead of==:if x = 5:is aSyntaxError. Use==to compare. - Forgetting the colon: every
if,elif, andelseline must end with:. - Wrong indentation: a missing or inconsistent indent raises an
IndentationError. Use four spaces and do not mix tabs and spaces. - Writing
else if: Python useselif. The two words are not accepted. - Writing
if x == 1 or 2:: this is always true, because2alone is truthy. Writex == 1 or x == 2, orx in (1, 2). - Wrong order of elif branches: with
score >= 60beforescore >= 90, a score of 95 gets the lower grade. Test the strictest condition first. - Comparing text to a number:
input()returns a string, so"5" == 5isFalse. Convert withint()first. - Using
isfor values: use==to compare numbers and strings, and keepisforNone. - An empty block: an
ifwith no body is a syntax error. Writepassas a placeholder until you add the code.
Key Takeaways
ifruns a block when its condition is true,eliftests further conditions, andelsecatches everything else.- Python checks the branches from top to bottom and runs only the first one that is true, so the order matters.
- Every condition line ends with a colon, and the block under it is indented, usually by four spaces.
- Comparison operators (
==,!=,<,>,<=,>=) and logical operators (and,or,not) build conditions. - Zero,
None,False, and empty collections are false. Other values are true. - Nested
ifstatements allow a second decision inside the first, but flatelifchains are often easier to read. - A conditional expression,
a if condition else b, picks one of two values in a single line.
Frequently Asked Questions
What is an if statement in Python?
An if statement runs a block of code only when its condition is true. It is written as the keyword if, a condition, and a colon, followed by an indented block. When the condition is false, Python skips the block and continues with the next unindented line.
What is the difference between if, elif, and else in Python?
The if statement starts a decision and tests the first condition. Each elif tests another condition only when all earlier ones were false. The else clause has no condition and runs when none of the earlier conditions were true. Only one block of the whole chain runs.
Does Python have else if?
No. Python uses the single keyword elif as a short form of else if. Writing else if on one line is a syntax error, because else must be followed directly by a colon.
How do I check more than one condition in Python?
Combine conditions with the logical operators and, or, and not. For example, if age >= 18 and has_ticket: runs only when both parts are true. You can also chain comparisons, such as 18 <= age < 65, or use an elif chain for separate cases.
What is the difference between = and == in Python?
A single equals sign assigns a value to a variable, as in x = 5. A double equals sign compares two values and returns True or False, as in x == 5. Using = inside an if condition causes a SyntaxError.
Which values are treated as False in a Python condition?
False, None, the number zero (0 and 0.0), and empty collections such as an empty string, list, tuple, dictionary, or set are all treated as false. Almost every other value is treated as true, including the string “False”.
What is a ternary operator in Python?
Python’s ternary operator is the conditional expression, written as value_if_true if condition else value_if_false. For example, parity = “even” if n % 2 == 0 else “odd” picks one of two values in a single line.
Does Python have a switch statement?
Python 3.10 and later have the match and case statement, which compares a value against several patterns. For simple choices an if, elif, else chain still works well, and it is the tool to learn first.