Python Conditions and if Statements
Conditions and if Statements
Programs constantly need to make decisions: Is the password correct? Is the item in stock? Has the user passed the exam? In Python, these decisions are made with conditional statements, and the most basic one is the if statement.
An if statement runs a block of code only when a condition is true. If the condition is false, Python skips that block and continues with the rest of the program.
Conditions and Comparison Operators
A condition is an expression that evaluates to True or False. Conditions are usually built with comparison operators, which come from basic mathematics and logic.
| Operator | Meaning | Example | Result (when a = 5, b = 3) |
|---|---|---|---|
== | Equal to | a == b | False |
!= | Not equal to | a != b | True |
< | Less than | a < b | False |
<= | Less than or equal to | a <= b | False |
> | Greater than | a > b | True |
>= | Greater than or equal to | a >= b | True |
These operators are used mainly in if statements, loops, and logical expressions to control the flow of a program.
Remember: A single
=assigns a value. A double==compares two values.
The if Statement
Syntax
if condition:
# code that runs only if the condition is True
The structure has three parts:
- The keyword
if - A condition, followed by a colon
: - An indented block of code — the body of the
ifstatement
Example: Comparing Two Values
x = 45
y = 30
if x > y:
print("x is larger than y")
Expected output:
x is larger than y
The condition x > y is 45 > 30, which is True, so Python runs the indented print() statement.
If you change y to 50, the condition becomes False, and nothing is printed.
How the if Statement Works
- Python evaluates the condition.
- The condition produces
TrueorFalse. - If the result is
True, the indented block runs. - If the result is
False, Python skips the block. - In either case, the program continues with the first line after the block.
temperature = 18
if temperature < 20:
print("It's cool today.")
print("Have a nice day!")
Expected output:
It's cool today.
Have a nice day!
The last print() is not indented, so it is not part of the if block. It runs no matter what the condition is.
Example: Checking Whether a Number Is Even
num = 8
if num % 2 == 0:
print("The number is even")
Expected output:
The number is even
How it works:
num % 2gives the remainder whennumis divided by 2.- For an even number, the remainder is
0. 8 % 2is0, so0 == 0isTrue, and the message is printed.
The Importance of Indentation
Python uses indentation to define code blocks. Many other languages use curly braces { }; Python does not.
Incorrect Indentation (Error)
marks = 75
if marks > 60:
print("You passed the exam")
Output:
IndentationError: expected an indented block after 'if' statement on line 2
Python requires at least one indented line after the colon.
Correct Indentation
marks = 75
if marks > 60:
print("You passed the exam")
Expected output:
You passed the exam
The standard indentation is 4 spaces.
Multiple Statements Inside an if Block
An if block can contain any number of statements. All of them must have the same indentation.
score = 92
if score >= 90:
print("Excellent performance!")
print("Grade: A")
print("Keep up the great work")
Expected output:
Excellent performance!
Grade: A
Keep up the great work
All three lines belong to the if block, so they run together when the condition is True — and are all skipped when it is False.
Using Variables Directly in Conditions
A Boolean variable already holds True or False, so it can be used directly as a condition without a comparison.
Example: Boolean Condition
has_permission = False
if has_permission:
print("Access granted")
Expected output: (nothing is printed)
has_permission is False, so the block is skipped. Writing if has_permission == True: works too, but if has_permission: is cleaner and is the standard Python style.
Truthy and Falsy Values in Conditions
Any value can be used as a condition. Empty values (0, "", [], {}, None) are treated as False; non-empty values are treated as True.
username = "asha_k"
if username:
print("Welcome,", username)
Expected output:
Welcome, asha_k
If username were an empty string "", nothing would be printed. This is a common way to check that input was provided.
Combining Conditions
Use the logical operators and, or, and not to build more complex conditions.
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("You may enter the event")
Expected output:
You may enter the event
Both conditions must be True for and to succeed.
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend")
Expected output:
It's the weekend
At least one condition must be True for or to succeed.
Practical Example: Free Shipping Check
cart_total = 1250
free_shipping_limit = 999
if cart_total >= free_shipping_limit:
print("You qualify for free shipping!")
print("Cart total:", cart_total)
Expected output:
You qualify for free shipping!
Cart total: 1250
Common Mistakes
| Mistake | Example | Result |
|---|---|---|
Using = instead of == | if x = 5: | SyntaxError |
| Forgetting the colon | if x > 5 | SyntaxError: expected ':' |
| Missing indentation | Body not indented | IndentationError |
| Inconsistent indentation inside the block | Mixing 4 and 2 spaces | IndentationError |
| Comparing strings with different case | if name == "asha" when name is "Asha" | Condition is False; use name.lower() |
What's Next?
An if statement on its own handles only the "true" case. In the next lessons, you will learn how to:
- Check several conditions in order with
elif - Handle the "otherwise" case with
else - Write compact one-line conditions with shorthand if
- Place
ifstatements inside otherifstatements with nested if
Related Concepts
- Python Booleans —
True,False, and truthy/falsy values - Python Operators — comparison and logical operators
- Python Syntax — indentation rules