A conditional lets your program make decisions. Instead of blindly running every line top to bottom, your program can ask a question — is this true? — and run different code depending on the answer. Conditionals are how programs respond to the world rather than just repeat the same thing every time.
1 What Is a Conditional?
Every day you make decisions based on conditions: if it is raining, take an umbrella. If the bus is full, walk instead. Programs do the same thing — they evaluate a condition, and depending on whether it is true or false, they follow a different path.
Imagine walking down a road and reaching a sign: "If you have a ticket, go left. Otherwise, go right." You read the condition (do you have a ticket?), answer it (yes or no), and your path branches accordingly. A conditional in Python is exactly this — a fork in the road that the program takes based on a true/false question.
In Python, the main tool for making decisions is the <strong>if</strong> statement. Here is the simplest possible example:
temperature = 35
if temperature > 30:
print("It is hot outside.")Python evaluates the condition temperature > 30. Because 35 > 30 is True, it runs the indented line. If temperature were 20, the condition would be False and the print would be skipped entirely.
2 Comparison Operators
A condition is built from a comparison — a question about how two values relate to each other. Python gives you six comparison operators. Every comparison produces a boolean result: either True or False.
| Operator | Meaning | Example | Result | Read it aloud as… |
|---|---|---|---|---|
== | Equal to | 5 == 5 | True | "Is 5 equal to 5?" |
!= | Not equal to | 5 != 3 | True | "Is 5 not equal to 3?" |
> | Greater than | 10 > 7 | True | "Is 10 greater than 7?" |
< | Less than | 3 < 1 | False | "Is 3 less than 1?" |
>= | Greater than or equal to | 5 >= 5 | True | "Is 5 greater than or equal to 5?" |
<= | Less than or equal to | 4 <= 10 | True | "Is 4 less than or equal to 10?" |
You can test any of these directly in Python, and Python will simply print True or False:
print(10 > 7) # True print(5 == 6) # False print(3 != 3) # False print(8 >= 8) # True
= is the assignment operator — it stores a value: score = 10.== is the comparison operator — it asks a question: score == 10.
Writing if score = 10: is a syntax error. Writing score == 10 outside a condition does nothing useful. Mixing these up is the single most common beginner mistake with conditionals. Read == aloud as "is equal to" to keep them straight.
2.1 Comparisons Work on Strings Too
Comparison operators are not just for numbers. You can compare strings with == and !=, which checks whether two pieces of text are exactly the same (including capitalisation):
username = "alex"
if username == "alex":
print("Welcome back, Alex!")
if username != "admin":
print("You do not have admin access.")"Alex" and "alex" are not equal in Python. String comparison is case-sensitive. "Alex" == "alex" evaluates to False. This catches many beginners off-guard when working with user input — if a user types "Alex" but your code checks for "alex", the condition will fail.
- What is the difference between
=and==? Give one example of each being used correctly. Predict whether each of these expressions is
TrueorFalse:100 == 100 99 != 100 50 >= 51 7 <= 7 "cat" == "Cat" "dog" != "fish"
- A student writes
if age = 18:. What kind of error is this, and how do you fix it? - Why might
username == "Admin"fail even if the user typed "admin"? How could you prevent this?
3 The in Operator
Python has a special operator that does something very useful: it checks whether one thing is contained inside another. This is the in operator, and it is one of Python's most readable features.
in works on two things you will use all the time:
- Strings — checking whether one piece of text appears inside another.
- Lists — checking whether a value exists anywhere in a collection. (You will learn more about lists in a later article — for now, just notice how natural the syntax feels.)
3.1 in with Strings
email = "[email protected]" if "school.edu" in email: print("This looks like a school email address.") if "@" in email: print("The email contains an @ symbol.")
Python reads "school.edu" in email almost like plain English: "is 'school.edu' found somewhere inside the email string?" If yes — True. If no — False.
3.2 in with Lists
allowed_users = ["alex", "sam", "priya"]
username = "sam"
if username in allowed_users:
print("Access granted.")Again, this reads almost like English: "if username is in the list of allowed users, grant access." This is one of the reasons Python is so readable — the code describes the logic directly.
3.3 not in — the Opposite
You can flip in to not in to check that something is absent:
banned_words = ["spam", "scam", "free money"]
message = "Click here for free money"
if "free money" in message:
print("This message looks like spam.")
vowels = ["a", "e", "i", "o", "u"]
letter = "b"
if letter not in vowels:
print(letter, "is a consonant.")Without in, checking whether a word appears in a string would require much more complex code. Python's in operator lets you express membership checks in one natural line. Whenever you find yourself asking "does this contain that?", in is almost certainly the right tool.
- What does the
inoperator check? Give one example using a string and one using a list. Predict the output of this program:
word = "programming" if "gram" in word: print("Found it!") if "z" not in word: print("No z here.")- A student wants to check whether a username is not in a list of banned users. Write the condition they should use.
- True or False:
"Python" in "I love Python programming"evaluates toTrue. Explain why.
4 Making a Choice: if and else
A bare if statement only does something when the condition is True — it stays silent when the condition is False. Often you want to handle both cases: do one thing if true, and a different thing if false. That is what else is for.
4.1 The Structure
if condition:
# runs when condition is True
else:
# runs when condition is FalseThere are a few rules to notice:
- The condition is followed by a colon
:. - The code to run is indented (one level in — 4 spaces is standard).
elsesits at the same indentation asif, also followed by a colon.- Only one branch runs — never both.
4.2 A Real Example
age = int(input("How old are you? "))
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")If the user types 20: Python evaluates 20 >= 18 → True → runs the if branch → prints "You are an adult." The else branch is skipped entirely.
If the user types 15: Python evaluates 15 >= 18 → False → skips the if branch → runs the else branch → prints "You are a minor."
4.3 What Happens Without else?
If you only write an if with no else, the program simply moves on silently when the condition is False. This is fine when you only care about the True case:
score = 95
if score == 100:
print("Perfect score!")
print("Thanks for playing.") # This always runsIf score is 95, the first print is skipped and only "Thanks for playing." appears. No error, no crash — Python just moves on.
5 Handling Multiple Cases: elif
What if you have more than two possible outcomes? if/else only handles two branches — true or false. For three or more cases, Python gives you elif, which is short for "else if".
Imagine a teacher marking exams. It is not simply "pass or fail" — there are five grades: A, B, C, D, and F. Each grade has its own score range. elif lets you check each range in order, stopping as soon as one matches. The moment Python finds a True condition, it runs that branch and skips everything else.
5.1 The Structure
if first_condition:
# runs if first_condition is True
elif second_condition:
# runs if first was False AND second_condition is True
elif third_condition:
# runs if first and second were False AND third_condition is True
else:
# runs if ALL conditions above were FalseKey rules:
- You can have as many
elifbranches as you need. - Python checks conditions top to bottom and stops at the first true one.
- The
elseat the end is optional — it is the "none of the above" case. - Only one branch ever runs, no matter how many conditions are listed.
5.2 A Full Grading Example
score = int(input("Enter your score (0-100): "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is:", grade)Notice that the conditions go from highest to lowest. Suppose the score is 85. Python checks:
• 85 >= 90 → False → move on.
• 85 >= 80 → True → grade = "B". Done. The remaining elifs and else are skipped.
What if the conditions were in the wrong order — say score >= 60 came first? A score of 85 would satisfy 85 >= 60 immediately and be labelled "D" — clearly wrong. Order is logic.
5.3 A Worked Trace Table
Good programmers trace their conditionals by hand before running the code. Here is a variable state table for the grading program above with a score of 73:
| Step | Condition checked | Result | Action |
|---|---|---|---|
| 1 | 73 >= 90 | False | Move to next condition. |
| 2 | 73 >= 80 | False | Move to next condition. |
| 3 | 73 >= 70 | True | Set grade = "C". Skip all remaining branches. |
| 4 | — | — | Print: "Your grade is: C" |
- What is the difference between
elseandelif? When would you use each? Trace this program with
temperature = 15. Which branch runs, and what is printed?if temperature >= 30: print("Hot day — wear sunscreen.") elif temperature >= 20: print("Warm day — a light jacket should do.") elif temperature >= 10: print("Cool day — bring a coat.") else: print("Cold day — wrap up well.")A student writes this grading program:
if score >= 60: grade = "D" elif score >= 70: grade = "C" elif score >= 80: grade = "B" elif score >= 90: grade = "A"What grade will a score of
95receive? What is wrong with this code, and how do you fix it?- How many branches of an
if/elif/elsechain can run at once? Explain why. - Write an
if/elif/elseblock that prints:- "Child" if age is under 13
- "Teenager" if age is 13–17
- "Adult" if age is 18 or over
6 Putting It All Together
Here is a complete program that combines everything in this article: comparison operators, the in operator, and an if/elif/else chain. Read it carefully and predict the output for a few different inputs before running it.
VIP_USERS = ["alice", "bob", "carol"]
username = input("Enter your username: ").lower()
score = int(input("Enter your score: "))
# Check access level
if username in VIP_USERS:
print("Welcome, VIP user", username + "!")
else:
print("Welcome,", username + ".")
# Check score and assign a rank
if score >= 90:
rank = "Gold"
elif score >= 70:
rank = "Silver"
elif score >= 50:
rank = "Bronze"
else:
rank = "Unranked"
print("Your rank is:", rank)
# Bonus message
if rank != "Unranked":
print("Congratulations on earning a rank!")A few things worth noticing in this program:
.lower()converts the username to lowercase before checking — so "Alice", "ALICE", and "alice" all match. This neatly solves the case-sensitivity problem from Section 2.- The two
ifblocks are independent — the access check and the rank check are separate decisions that do not interact. - The final
ifuses a!=comparison against the string"Unranked"to decide whether to print the bonus message.
7 Common Mistakes to Watch For
| Mistake | What it looks like | Why it happens | How to fix it |
|---|---|---|---|
Using = instead of == | if score = 10: | Confusing assignment with comparison. | Change to if score == 10: |
| Forgetting the colon | if score > 50 | Every if, elif, and else line ends in :. | Add the colon: if score > 50: |
| Wrong indentation | Body of the if not indented, or indented inconsistently. | Python uses indentation as structure — it is not optional. | Indent the body exactly 4 spaces. Use the Tab key consistently. |
| Conditions in the wrong order | Checking score >= 60 before score >= 90. | Every score above 60 matches the first condition, so the rest never run. | Always order conditions from most specific (highest) to least specific (lowest). |
| Case-sensitive string comparison | Checking == "yes" when user might type "Yes" or "YES". | String comparisons are exact — capitalisation counts. | Use .lower() to normalise before comparing. |
| Comparing a string to a number | age = input(...) then if age >= 18: | input() always returns a string — you cannot compare it to an integer. | Convert first: age = int(input(...)) |
8 Final Check: The Big Picture
Conditionals let programs make decisions. A comparison operator asks a true/false question about two values. The <strong>in</strong> operator checks whether something is contained inside a string or list. An <strong>if</strong> statement runs a block of code when a condition is true. <strong>elif</strong> adds more cases. <strong>else</strong> handles everything that didn't match. Only one branch ever runs. Order matters.
- In your own words, explain what a conditional does. Why are conditionals essential in real programs?
Trace this program with
item = "sword". Write down exactly what is printed, step by step.inventory = ["shield", "potion", "map"] item = "sword" if item in inventory: print(item, "is already in your inventory.") elif len(item) > 5: print(item, "is a long word but not in your inventory.") else: print(item, "is short and not in your inventory.")- Write a program that:
- Asks the user to enter a password.
- Prints "Access granted" if the password is "python99".
- Prints "Wrong password" otherwise.
- A program is supposed to print "Freezing" below 0°C, "Cold" from 0–9°C, "Mild" from 10–19°C, and "Warm" at 20°C and above. A student writes it with
if temperature >= 0as the first condition. What goes wrong for a temperature of-5? Fix the program. What is the output of this program? Trace it carefully.
x = 42 if x > 100: print("big") elif x > 50: print("medium") elif x > 10: print("small") else: print("tiny")
9 Quick-Reference: Operators at a Glance
| Operator | Type | What it asks | Example → Result |
|---|---|---|---|
== | Comparison | Are these two values equal? | 5 == 5 → True |
!= | Comparison | Are these two values different? | 5 != 3 → True |
> | Comparison | Is the left value greater? | 10 > 7 → True |
< | Comparison | Is the left value smaller? | 3 < 1 → False |
>= | Comparison | Is the left value greater than or exactly equal? | 5 >= 5 → True |
<= | Comparison | Is the left value smaller than or exactly equal? | 4 <= 10 → True |
in | Membership | Is this value found inside that string or list? | "a" in "cat" → True |
not in | Membership | Is this value absent from that string or list? | "z" not in "cat" → True |