Python if...else Statements: Choosing Between Two Outcomes
Learn how Python if...else statements choose between two code paths using conditions, comparisons, user input, age checks, and even-or-odd examples.
An if...else statement lets a Python program make a two-way decision. When a condition is true, Python runs one block of code. When the condition is false, Python runs a different block.
For example, a program can check whether someone is at least 21 years old and display one message for people who meet the requirement and another message for people who do not.
How an if...else Decision Works
An if statement is a control-flow statement that runs an indented block only when its condition is true. An else clause is the fallback branch paired with an if statement. It runs when the if condition is false.
A condition is an expression evaluated as true or false. The two possible truth values are called Boolean values: True and False.
A simple if...else statement always chooses exactly one of its two branches for each evaluation:
| Condition result | Block that runs | Block that is skipped |
|---|---|---|
| True | if block | else block |
| False | else block | if block |
If the condition is true, the else block is skipped. If the condition is false, the if block is skipped.
Basic if...else Syntax
if condition:
statements_when_true
else:
statements_when_false
ifbegins the decision.conditionis evaluated asTrueorFalse.- The colon after the condition is required.
- Statements under
ifmust be indented. elseintroduces the alternative branch and does not have its own condition.- The colon after
elseis also required. - Statements under
elsemust be indented.
Python uses indentation, or leading whitespace, to define which statements belong to a code block. Four spaces per level is the usual convention. Keep indentation consistent within both branches.
temperature = 30
if temperature >= 25:
print("It is warm.")
else:
print("It is cool.")
The comparison operator >= means “greater than or equal to.” If temperature is 25 or higher, the first message is printed; otherwise, the second message is printed. For more comparison operators, see Python comparison operators.
Conditions and Comparison Operators
A comparison operator compares values and produces a Boolean value. Common comparisons used with if...else include:
| Operator | Meaning | Example | Result |
|---|---|---|---|
> | greater than | 8 > 3 | True |
>= | greater than or equal to | 21 >= 21 | True |
< | less than | 2 < 5 | True |
== | equal to | 4 == 4 | True |
!= | not equal to | 4 != 7 | True |
Do not confuse ==, which tests equality, with =, which assigns a value to a variable. For example, number % 2 == 0 asks whether a remainder equals zero.
Using User Input in a Decision
The input() function reads a response from the user and returns it as a string, which means text. Even if the user types digits, the returned value is still text.
Use int() to convert valid integer text into an integer before performing numeric comparisons:
age = int(input("How old are you? "))
This stores the converted value in the variable age. You can then use that variable in a condition. The int() function works with whole-number text such as "21", but invalid text such as "twenty-one" causes a ValueError.
For more practice reading responses, see getting user input in Python.
Example: Eligibility Based on Age
This program asks for a person's name and age. It compares the age with the threshold of 21. An age of exactly 21 meets the requirement because the condition uses >=.
name = input("Name: ")
age = int(input("Age: "))
if age >= 21:
print(name, "meets the age requirement.")
else:
print(name, "does not meet the age requirement.")
Sample Run: Below the Threshold
Name: Mark
Age: 19
Mark does not meet the age requirement.
Here, age >= 21 is false, so Python skips the if block and runs the else block.
Sample Run: Meeting the Threshold
Name: Mark
Age: 21
Mark meets the age requirement.
Here, age >= 21 is true, so Python runs the if block and skips the else block.
Example: Checking Whether a Number Is Even or Odd
The modulo operator, written as %, returns the remainder after division. An even number is divisible by 2 with a remainder of zero. An odd number leaves a remainder of one when divided by 2.
number = int(input("Enter an integer: "))
# A zero remainder means the number is divisible by 2.
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
The expression number % 2 calculates the remainder. The comparison == 0 turns that calculation into a Boolean condition.
| Number | Number % 2 | Classification |
|---|---|---|
| 5 | 1 | Odd |
| 67 | 1 | Odd |
| 100 | 0 | Even |
Sample Run with an Odd Number
Enter an integer: 5
The number is odd.
Sample Run with an Even Number
Enter an integer: 100
The number is even.
The comment beginning with # explains the remainder-based test. Comments do not affect program execution; Python ignores them when running the program. See using comments in Python for more about documenting code.
if...else Compared with an if Statement Alone
An if statement without an else branch runs its block only when the condition is true. If the condition is false, it simply continues with the next statement.
score = 42
if score >= 50:
print("You passed.")
print("The check is complete.")
This is different from if...else, which provides a result for both outcomes:
score = 42
if score >= 50:
print("You passed.")
else:
print("You did not pass.")
Use if...else when the program must choose between two alternatives. Use an if statement alone when nothing needs to happen for a false condition.
Common Errors and Troubleshooting
Inconsistent indentation
Problem: Python reports an IndentationError, or a statement appears to run outside the intended branch.
Cause: Statements below if or else are not consistently indented.
Fix: Indent every statement in a branch by the same amount, commonly four spaces:
if age >= 21:
print("Allowed.")
else:
print("Not allowed.")
Missing colons
Problem: A SyntaxError points near if or else.
Fix: Add a colon after both branch headers:
if condition:
print("True branch")
else:
print("False branch")
Comparing text with a number
Problem: A numeric comparison involving entered input fails or behaves unexpectedly.
Cause: input() returned text instead of an integer.
Fix: Convert the response with int():
age = int(input("Age: "))
Incorrect even-number condition
Problem: The program labels numbers incorrectly.
Fix: Test whether the remainder is zero, using equality comparison:
if number % 2 == 0:
Do not replace == with the assignment operator =.
Unexpected else output at a boundary
Problem: The else message appears when an age such as 21 was expected to meet the requirement.
Fix: Check the comparison operator. age >= 21 includes 21, while age > 21 does not. Also verify that the converted age has the expected value.
Non-numeric input
Problem: Entering non-numeric text causes a ValueError.
Cause: int() can convert valid integer text only.
Fix: Enter a whole number for these examples. Input validation with exception handling can be added later.
Key Points to Remember
if...elseis a two-way decision structure.- The condition controls which of two alternative code paths runs.
- The if suite runs for
True; the else suite runs forFalse. - Both
if condition:andelse:require colons. - Indentation defines the statements belonging to each branch.
elsehas no condition of its own; it handles the false result of the if condition.input()returns text, so useint()before comparing numeric input with numbers.- Use
%to calculate a remainder, andnumber % 2 == 0to test for an even number. - Exactly one branch of a simple if...else statement executes for each evaluation.