Kahibaro
Discord Login Register

Common beginner mistakes

Typical If/Else Mistakes (and How to Fix Them)

This chapter focuses on common mistakes with conditions and how to avoid them. You already know what if, elif, else, comparison operators, and logical operators do; here we look at how beginners often use them incorrectly.

Think of this as a checklist to run through when your conditions “don’t work.”


1. Using `=` Instead of `==` in Conditions

The mistake

= is for assignment, == is for comparison.

age = 18
# ❌ Wrong: using assignment in an if condition
if age = 18:
    print("You are 18")

This causes a syntax error.

The fix

Use == when you want to check if two values are equal.

age = 18
# ✅ Correct
if age == 18:
    print("You are 18")

Quick memory trick:

2. Forgetting the Colon `:` After `if`, `elif`, or `else`

Every if, elif, and else line must end with a colon.

The mistake

temperature = 30
# ❌ Missing colon
if temperature > 25
    print("It's warm")

This gives a syntax error.

The fix

temperature = 30
# ✅ With colon
if temperature > 25:
    print("It's warm")

Same for elif and else:

if temperature > 25:
    print("Warm")
elif temperature > 15:
    print("Mild")
else:
    print("Cold")

3. Wrong Indentation Inside Conditions

Python uses indentation to know which lines belong to an if, elif, or else block.

The mistake

number = 10
# ❌ Inconsistent indentation
if number > 5:
print("Greater than 5")       # Not indented -> error
    print("Still inside if")  # Over-indented

This will cause an IndentationError or behave unexpectedly.

The fix

Indent all lines inside the block by the same amount (typically 4 spaces).

number = 10
# ✅ Proper indentation
if number > 5:
    print("Greater than 5")
    print("Still inside if")

Also make sure elif and else are aligned with the if:

score = 75
# ✅ All at the same level
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("Below B")

4. Misunderstanding `if` vs `elif` vs Multiple `if`s

The mistake: Using multiple `if` statements when you really want **only one** branch to run.

score = 85
# ❌ Every if is checked separately
if score >= 90:
    print("A")
if score >= 80:
    print("B")
if score >= 70:
    print("C")

Output:

B
C

Because score >= 80 and score >= 70 are both true.

The fix: Use `if` / `elif` / `else` for **mutually exclusive** cases.

score = 85
# ✅ Only one block runs
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("Below C")

Use separate ifs only when you really want to check all conditions independently.


5. Writing Conditions That Are Always True or Always False

Sometimes logic is technically valid but doesn’t do what you mean.

Always true example

age = 20
# ❌ Always true for ages 18 or older
if age >= 18 or age <= 30:
    print("In range")

For any age, the condition is actually always true, because:

Result: "In range" prints even for age 5.

The fix: Use `and` when you mean “between”

age = 20
# ✅ Age between 18 and 30 (inclusive)
if age >= 18 and age <= 30:
    print("In range")

Or more compactly:

if 18 <= age <= 30:
    print("In range")

When your program behaves strangely, double-check if your condition is always true or always false due to how you combined comparisons.


6. Confusing `and` and `or`

`and` means: **both** conditions must be true.

`or` means: **at least one** condition must be true.

Common mistake

Assume you want to check if color is "red" or "blue".

color = "red"
# ❌ This does not do what it looks like
if color == "red" or "blue":
    print("Color is red or blue")

This condition is always true because "blue" by itself is treated as a true value.

The fix

Repeat the variable on both sides:

color = "red"
# ✅ Correct
if color == "red" or color == "blue":
    print("Color is red or blue")

Or use in with a collection:

# ✅ More concise
if color in ("red", "blue"):
    print("Color is red or blue")

7. Using `if` Instead of `elif` for Ranges

Another version of the “multiple ifs” mistake is with ranges.

The mistake

score = 95
# ❌ Overlapping ranges with multiple ifs
if score >= 90:
    print("Excellent")
if score >= 80:
    print("Good")
if score >= 70:
    print("Okay")

Result:

Excellent
Good
Okay

The fix

Use elif so only the first matching condition runs.

score = 95
# ✅ Use elif for ranges
if score >= 90:
    print("Excellent")
elif score >= 80:
    print("Good")
elif score >= 70:
    print("Okay")
else:
    print("Needs improvement")

8. Relying on Exact String Matches (And Getting Them Wrong)

Conditions with strings must match exactly, including upper/lower case and extra spaces.

The mistake

answer = "Yes"
# ❌ Case-sensitive mismatch
if answer == "yes":
    print("You said yes")

Nothing prints because "Yes" is not equal to "yes".

Sometimes there are hidden spaces:

answer = input("Continue? (yes/no): ")
# User types: "yes " (with a space)
if answer == "yes":
    print("Continuing...")

The condition is false because "yes " is not "yes".

The fix

Make the comparison more forgiving:

answer = input("Continue? (yes/no): ")
# ✅ Normalize input
answer = answer.strip().lower()
if answer == "yes":
    print("Continuing...")
elif answer == "no":
    print("Stopping.")
else:
    print("Invalid answer")

9. Comparing Strings Instead of Numbers

Input from the user is a string by default. Forgetting this can break numeric comparisons.

The mistake

age = input("Enter your age: ")
# ❌ Comparing string to number (or string-to-string numerically)
if age > 18:
    print("Adult")

This either causes an error (string vs number) or behaves incorrectly if both sides are strings (because "20" > "100" in string comparison).

The fix

Convert the input to a number before comparing.

age = int(input("Enter your age: "))
# ✅ Now age is an int
if age > 18:
    print("Adult")
else:
    print("Not an adult")

If the conversion might fail (user types non-numbers), you’ll handle that with error handling, which is covered later. For now, be sure you’re comparing numbers with numbers, not strings with numbers.


10. Misunderstanding Truthy and Falsy Values

In conditions, Python doesn’t only accept True or False. It also treats some values as false (falsy) and others as true (truthy).

Common falsy values:

Everything else is generally truthy.

The mistake

Assuming 0 or "" will act like “no value” in your logic without thinking about it.

count = 0
# ❌ Might be surprising
if count:
    print("There are items")
else:
    print("No items")

This prints "No items" because 0 is falsy.

The fix

Be explicit about what you mean:

count = 0
# ✅ Clearer intention
if count > 0:
    print("There are items")
else:
    print("No items")

Similarly for strings:

name = ""
# ✅ Check for empty string
if name == "":
    print("No name given")

Or:

if not name:
    print("No name given")

11. Forgetting That `else` Catches “Everything Else”

else runs when none of the previous conditions are true. Sometimes beginners assume else is tied to the last condition only.

The mistake

temperature = 5
if temperature > 25:
    print("Warm")
elif temperature > 15:
    print("Mild")
else:
    # ❌ Assuming this is only for "cold but above 0"
    print("Cold but not freezing")

For temperature = -5, the else block still runs, printing "Cold but not freezing", which is logically wrong.

The fix

Write conditions so that the else message is correct for all remaining cases, or add another elif.

temperature = -5
if temperature > 25:
    print("Warm")
elif temperature > 15:
    print("Mild")
elif temperature >= 0:
    print("Cold but not freezing")
else:
    print("Freezing")

12. Overcomplicating Conditions

Beginners often write very long, hard-to-read conditions.

The mistake

age = 25
has_ticket = True
is_vip = False
# ❌ Hard to read
if (age >= 18 and has_ticket == True and is_vip == False) or (age >= 21 and has_ticket == True):
    print("Allowed in")

The fix

age = 25
has_ticket = True
is_vip = False
# ✅ Simpler conditions
is_adult = age >= 18
is_21_or_older = age >= 21
if (is_adult and has_ticket and not is_vip) or (is_21_or_older and has_ticket):
    print("Allowed in")

Or rethink the rules and simplify the logic itself if possible.


13. Forgetting That `elif` Is Only Checked If Previous Conditions Are False

If an if condition is true, Python skips all the following elifs and else.

The mistake

Expecting later elifs to “correct” an earlier decision.

age = 17
if age >= 16:
    print("Can drive")
elif age < 18:
    print("Too young to drive")  # ❌ This will never run for age >= 16

Here, for age 17:

The fix

Order your conditions from most specific to more general, or rewrite them.

age = 17
if age < 16:
    print("Too young to drive")
elif age < 18:
    print("Can drive with restrictions")
else:
    print("Can drive freely")

14. Practical Debugging Tips for Conditions

When a condition “should be true” but isn’t, or vice versa, try:

  1. Print the values used in the condition.
   age = int(input("Age: "))
   print("DEBUG age:", age)
   if age >= 18:
       print("Adult")
   else:
       print("Not adult")
  1. Print the condition result directly.
   age = int(input("Age: "))
   print("DEBUG check:", age >= 18)  # Shows True or False
   if age >= 18:
       print("Adult")
   else:
       print("Not adult")
  1. Simplify the condition:
    • Break a long condition into smaller ones.
    • Test each part separately.
  2. Check types:
    • Use type(value) to make sure you’re not comparing strings to numbers.
   age = input("Age: ")
   print(type(age))  # Probably <class 'str'>

15. Quick Checklist When `if`/`else` “Doesn’t Work”

Run through this list:

If you go through these points, you’ll catch most common condition bugs very quickly.

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!