Python if Statements: Making Decisions with Conditions
Learn how Python if statements evaluate conditions, use True and False, compare values with ==, and control indented blocks of code.
What an if statement does
An if statement is a conditional statement that controls whether a block of code runs. Python evaluates a condition, then performs the action in the indented block only when that condition is true.
If the condition is false, Python skips every statement in that indented block. The program continues with the next statement after the block.
temperature = 25
if temperature == 25:
print("The temperature is 25 degrees.")Here, Python checks the condition temperature == 25. Because the condition is true, the print() statement runs.
Basic if statement syntax
The essential structure of an if statement is:
if condition:
statementPython evaluates the condition before it considers executing the block. The colon is required, and the statement controlled by the condition must be indented.
Boolean condition evaluation
A condition produces a Boolean result. A Boolean is a logical value that is either True or False.
- True: The condition is satisfied, so the if block executes.
- False: The condition is not satisfied, so the if block is skipped.
Comparison expressions commonly produce Boolean results. For example:
print(5 == 5) # True
print(5 == 8) # FalseIndentation defines the code block
Indentation is the whitespace at the beginning of a line. In Python, indentation defines which statements belong to a code block. Use four spaces for each indentation level.
A one-line conditional block looks like this:
score = 100
if score == 100:
print("Perfect score!")Multiple statements can belong to the same block when they have the same indentation:
score = 100
if score == 100:
print("Perfect score!")
print("Display a congratulations message.")Both indented print() statements run when the condition is true. A statement with no indentation belongs outside the block:
score = 100
if score == 100:
print("Perfect score!")
print("This line runs after the if statement.")Missing or inconsistent indentation can cause an IndentationError or an unexpected indent error. Mixing tabs and spaces can also make indentation inconsistent. Prefer four spaces and configure your editor to insert spaces.
Comparing values with ==
The equality operator, ==, checks whether two values are equal. It is a type of comparison operator because it compares values and produces True or False.
Numeric comparison:
expected = 7
if expected == 7:
print("The number matches.")String comparison:
color = "blue"
if color == "blue":
print("The selected color is blue.")The variable is evaluated first, and then its current value is compared with the value on the other side of ==.
Assignment = versus equality ==
The single equals sign, =, is the assignment operator. It stores a value in a variable. The double equals sign, ==, tests whether two values are equal.
Assign a value before testing it:
x = 5
if x == 5:
print("x contains 5.")A common beginner mistake is using = in an if condition:
x = 5
# Incorrect: do not use assignment as the condition
# if x = 5:Use = to assign and == to compare. A line such as if x = 5: causes a SyntaxError because an if condition must be an expression that can be evaluated, not an assignment written in this form.
True and false examples
When the comparison is true, the indented output statement runs:
number = 10
if number == 10:
print("The number matches 10.")Output:
The number matches 10.Changing only the value being compared makes the condition false:
number = 10
if number == 20:
print("The number matches 20.")This program produces no output. The print() statement is skipped because number == 20 evaluates to False. An if statement does not automatically print a message when its condition is false.
Using strings in conditions
Text values, called strings, can also be compared with ==. This allows code to perform an action for a particular name or other exact text value.
name = "Maya"
if name == "Maya":
print("Hello, Maya!")Output:
Hello, Maya!String comparison depends on the exact value, including capitalization, spelling, and spaces. For example, "Maya" and "maya" are different strings:
name = "maya"
if name == "Maya":
print("Hello, Maya!")This produces no output because the two strings do not match exactly. Learn more about Python strings and comparison operators.
Putting the parts together
This example assigns a value, evaluates a comparison, and runs two statements in one conditional block:
expected_number = 42
if expected_number == 42:
print("The answer is correct.")
print("Continue to the next step.")- Python assigns
42toexpected_number. - Python evaluates
expected_number == 42. - The comparison produces
True. - Both statements at the same indentation level run.
Troubleshooting if statements
Using = instead of ==
If you confuse assignment with comparison, check that the variable is assigned before the conditional and that the condition uses ==.
Indentation errors
Make sure every statement controlled by the if statement is indented consistently, preferably by four spaces. If a statement should run only when the condition is true, it must be inside the indented block.
Missing colon
A SyntaxError on the if line often means the colon is missing. Write the header with a colon before the block:
if x == 5:
print("x is 5.")Expected text is not printed
First check whether the condition is false. Inspect the variable's current value and the value being compared. For strings, check capitalization, spelling, and spaces.
A statement runs unexpectedly
If a statement runs even though it should be conditional, it may be outside the indented block. Move it to the same indentation level as the other statements controlled by the condition.
Key points
- An if statement runs an indented code block only when its condition is
True. - A condition produces either
TrueorFalse. - The colon ends the if header.
- Indentation defines the statements in the code block; four spaces is the recommended style.
- Use
=for assignment and==for equality comparison. - Numbers and strings can be compared, but strings must match exactly, including capitalization.
- When the condition is
False, Python skips the block and produces no output from it.