Programs need to make decisions: give a discount if the bill is over ₹500, show an error if the password is wrong, print "pass" or "fail" depending on the marks. In Python, decisions are made with if, elif and else.
This guide covers comparison and logical operators, if/elif/else, nested conditions, truthy values and the one-line conditional expression.
The if statement
marks = 72
if marks >= 40:
print("Pass")
print("Well done")
print("Result printed") # always runs
- The condition is followed by a colon.
- The lines that belong to the
ifare indented, usually by four spaces. Python uses indentation, not curly braces, to group code. - The indented block runs only when the condition is
True.
if and else
else runs when the condition is False:
age = 16
if age >= 18:
print("You can vote")
else:
print("Too young to vote")
elif: more than two choices
elif (short for "else if") checks another condition. Python checks from the top and runs only the first block whose condition is true:
marks = 82
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "C"
print(grade) # A
Order matters. If marks >= 60 came first, 82 would get a "B", because Python would stop at the first match.
Comparison operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 7 > 9 | False |
< | Less than | 2 < 9 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 4 <= 3 | False |
A single = assigns a value; a double == compares. Writing if marks = 40: is a SyntaxError.
Python lets you chain comparisons, which reads like maths:
if 18 <= age <= 60:
print("Working age")
Logical operators: and, or, not
| Operator | True when | Example |
|---|---|---|
and | Both sides are true | age >= 18 and has_id |
or | At least one side is true | day == "Sat" or day == "Sun" |
not | The value is false | not is_banned |
username = "ahana"
password = "secret123"
if username == "ahana" and password == "secret123":
print("Logged in")
else:
print("Wrong username or password")
To check against several values, in is shorter than many ors:
if day in ("Sat", "Sun"):
print("Weekend")
Truthy and falsy values
A condition doesn't have to be a comparison. Empty strings and lists, 0 and None count as false; most other values count as true:
name = input("Name: ")
if name:
print(f"Hello, {name}")
else:
print("You didn't type a name")
Nested conditions
An if can sit inside another if:
bill = 650
is_member = True
if bill > 500:
if is_member:
discount = 0.15
else:
discount = 0.10
else:
discount = 0
print(f"Pay ₹{bill * (1 - discount):.2f}") # Pay ₹552.50
Deep nesting gets hard to read. Often and or elif can flatten it.
The one-line conditional expression
For a simple choice between two values, Python has a short form, often called the ternary operator:
status = "adult" if age >= 18 else "minor"
It reads as "status is adult if age is at least 18, else minor".
Common mistakes
| Mistake | Problem | Fix |
|---|---|---|
if x = 5: | = assigns | Use == |
| Missing colon | SyntaxError | if x > 5: |
| Wrong indentation | IndentationError, or the wrong lines run | Indent every line of the block by 4 spaces |
if x == 1 or 2: | Always true, because 2 is truthy | if x == 1 or x == 2: or if x in (1, 2): |
| Comparing input to a number | input() returns a string, so "5" == 5 is False | Convert with int() first |
Practice
- Ask for a number and print whether it is even or odd.
Show the answer
n = int(input("Number: "))
if n % 2 == 0:
print("Even")
else:
print("Odd")
- Print the largest of three numbers
a,bandcwithout usingmax().
Show the answer
a, b, c = 12, 45, 30
if a >= b and a >= c:
largest = a
elif b >= c:
largest = b
else:
largest = c
print(largest) # 45
- A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Check a year.
Show the answer
year = 2024
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")
1900 is not a leap year; 2000 and 2024 are.
- Electricity costs ₹5 per unit for the first 100 units and ₹8 per unit after that. Calculate the bill for 160 units.
Show the answer
units = 160
if units <= 100:
bill = units * 5
else:
bill = 100 * 5 + (units - 100) * 8
print(bill) # 980
Interview questions
What is the difference between = and ==?
= assigns a value to a variable. == compares two values and returns True or False.
What is the difference between == and is?
== checks whether two values are equal. is checks whether two names point to the very same object. Use is only for None, as in if x is None:.
What is short-circuit evaluation?
and stops as soon as one side is false, and or stops as soon as one side is true, without evaluating the rest. So in if items and items[0] > 5:, the second check never runs on an empty list, which avoids an IndexError.
Does Python have a switch statement?
Since Python 3.10, the match statement does pattern matching, which covers what switch does in other languages and more. Before that, people used if/elif chains or a dictionary that maps each value to a result.
What to learn next
- Repeat work with Python for and while loops.
- Put your conditions inside reusable Python functions.