Academic Block

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 the if condition is false.
  • elif: checks another condition when the earlier ones were false.
  • Conditions: expressions that give True or False, 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.

What this code does: It stores a temperature and checks whether it is above 30. If it is, the indented line prints a message. The last line is not indented, so it runs every time.
temperature = 31
if temperature > 30:
    print("It is hot today")
print("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.

What this code does: It checks whether the remainder of 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")

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.

What this code does: It checks a score against several limits from highest to lowest and stores a matching grade in a variable. The last line prints the score and the grade.
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}")

Logical Operators and Combined Conditions

The logical operators and, or, and not combine conditions into larger ones.

  • a and b is true only when both parts are true.
  • a or b is true when at least one part is true.
  • not a reverses 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.

What this code does: It prints the results of a chained comparison and of conditions combined with 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)

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.

What this code does: It uses an empty string and a list directly as conditions, without any comparison operator. It then combines a membership test with 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")

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.

What this code does: It chooses a ticket price from a person’s age. For people under 18 it asks a second question, whether they are a student, using a nested 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)

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.

What this code does: It uses a conditional expression to label a number as even or odd, and a chained one to label a temperature as cold, warm, or hot. It then uses 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")
Tip: Write the most likely or most important case first, keep each branch short, and give variables clear names such as is_student or has_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.

What this code does: It reads a whole number and uses an 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")

Try It: A Leap Year Checker

The Program Input box is filled with 2024. Click Run Code, then try 1900, 2000, and 2026.

What this code does: It reads a year and applies the leap year rule in a single condition. A year is a leap year when it is divisible by 400, or when it is divisible by 4 but not by 100.
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")

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.

What this code does: It reads a purchase amount and a membership answer. It picks a discount with an 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}")

Common Mistakes with Conditions

  • Using = instead of ==: if x = 5: is a SyntaxError. Use == to compare.
  • Forgetting the colon: every if, elif, and else line 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 uses elif. The two words are not accepted.
  • Writing if x == 1 or 2:: this is always true, because 2 alone is truthy. Write x == 1 or x == 2, or x in (1, 2).
  • Wrong order of elif branches: with score >= 60 before score >= 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" == 5 is False. Convert with int() first.
  • Using is for values: use == to compare numbers and strings, and keep is for None.
  • An empty block: an if with no body is a syntax error. Write pass as a placeholder until you add the code.

Key Takeaways

  • if runs a block when its condition is true, elif tests further conditions, and else catches 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 if statements allow a second decision inside the first, but flat elif chains 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.

Ready for the next step?Learn how to match a value against several patterns.
Next: match / case →