DEV Community

Cover image for How Your Code Makes Decisions (And Gets Them Wrong)
Akhilesh
Akhilesh

Posted on

How Your Code Makes Decisions (And Gets Them Wrong)

Picture this

You're building a simple app. It checks if someone is old enough to sign up. Sounds easy. You have their age. You know the minimum age. You just need the program to say yes or no.

But you don't know how to make the program choose. Right now your code just runs top to bottom, every line, every time. It doesn't skip anything. It doesn't branch. It has no judgment.

That changes today.


The ability to make decisions is what separates a real program from a list of instructions. Without it, every program would do the exact same thing every single time, no matter what. No reactions. No logic. No intelligence.

If/else is how you give your code judgment.


The Basic Idea

An if statement says: check this condition. If it's true, run this code. If it's not true, skip it.

That's really all it is.

age = 20

if age >= 18:
    print("You can sign up")
Enter fullscreen mode Exit fullscreen mode

Output:

You can sign up
Enter fullscreen mode Exit fullscreen mode

Now change age to 15 and run it again.

age = 15

if age >= 18:
    print("You can sign up")
Enter fullscreen mode Exit fullscreen mode

Output:


Enter fullscreen mode Exit fullscreen mode

Nothing. The condition was false so Python skipped the whole block.


The Structure, Explained Line by Line

if age >= 18:
    print("You can sign up")
Enter fullscreen mode Exit fullscreen mode

if is the keyword that starts a decision.

age >= 18 is the condition. Python checks this. It becomes either True or False.

The colon : at the end of the if line is required. Forget it and you get an error.

print("You can sign up") is indented with 4 spaces. This is the block of code that runs when the condition is true. The indentation is how Python knows which code belongs to the if.

This is important. Python uses indentation to understand structure. Not brackets, not semicolons, spaces. If your indentation is wrong, your code either crashes or does the wrong thing.


Adding the Else

What if you want something to happen when the condition is false too?

age = 15

if age >= 18:
    print("You can sign up")
else:
    print("Sorry, you need to be 18 or older")
Enter fullscreen mode Exit fullscreen mode

Output:

Sorry, you need to be 18 or older
Enter fullscreen mode Exit fullscreen mode

else catches everything the if didn't. It runs when the condition is false. No condition needed for else, it's the default path.

Change age to 25. The if runs, the else gets skipped. Change it to 10. The if gets skipped, the else runs. The two blocks are mutually exclusive. Only one ever runs.


More Than Two Options: elif

Sometimes two options aren't enough.

score = 72

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")
Enter fullscreen mode Exit fullscreen mode

Output:

Grade: C
Enter fullscreen mode Exit fullscreen mode

elif means "else if." It gives you additional conditions to check after the first one fails.

Python checks from top to bottom and stops at the first true condition. Score is 72. Is it 90 or above? No. Is it 80 or above? No. Is it 70 or above? Yes. Print "Grade: C." Stop. The remaining elif and the else are ignored.

This is why order matters. If you put score >= 60 first, a score of 95 would print "Grade: D" because 95 is also above 60 and Python would stop there.

Try flipping the order and see what happens. Breaking things on purpose is one of the best ways to understand how they work.


The Comparison Operators

You've seen >= already. Here are all the ways you can compare things.

a = 10
b = 3

print(a == b)    # equal to: False
print(a != b)    # not equal to: True
print(a > b)     # greater than: True
print(a < b)     # less than: False
print(a >= b)    # greater than or equal to: True
print(a <= b)    # less than or equal to: False
Enter fullscreen mode Exit fullscreen mode

The one that trips people up most is ==. In Python, one equals sign = means assignment. Put a value into a variable. Two equals signs == means comparison. Are these two things equal?

Inside an if statement, you almost always want ==. Using = inside an if is one of the most common early mistakes.


Combining Conditions

What if you need two things to be true at the same time?

age = 20
has_id = True

if age >= 18 and has_id:
    print("Come on in")
else:
    print("Can't let you in")
Enter fullscreen mode Exit fullscreen mode

Output:

Come on in
Enter fullscreen mode Exit fullscreen mode

and requires both conditions to be true. If either one is false, the whole thing is false.

What if either condition being true is enough?

is_member = False
has_coupon = True

if is_member or has_coupon:
    print("You get a discount")
else:
    print("Full price for you")
Enter fullscreen mode Exit fullscreen mode

Output:

You get a discount
Enter fullscreen mode Exit fullscreen mode

or only needs one condition to be true.

And not flips a boolean. not True becomes False. not False becomes True.

is_raining = False

if not is_raining:
    print("Good day for a walk")
Enter fullscreen mode Exit fullscreen mode

Output:

Good day for a walk
Enter fullscreen mode Exit fullscreen mode

Conditions Inside Conditions

You can put if statements inside other if statements. This is called nesting.

age = 20
has_ticket = True

if age >= 18:
    if has_ticket:
        print("Enjoy the show")
    else:
        print("You need a ticket")
else:
    print("Must be 18 or older")
Enter fullscreen mode Exit fullscreen mode

Output:

Enjoy the show
Enter fullscreen mode Exit fullscreen mode

Each level of nesting gets another level of indentation. Works fine, but don't go too deep. After three or four levels it becomes hard to read. You'll learn cleaner ways to handle complex conditions as you go.


A Real Example

Let's build something slightly more real. A simple login check.

correct_username = "alex123"
correct_password = "python2024"

username = "alex123"
password = "wrongpassword"

if username == correct_username and password == correct_password:
    print("Login successful. Welcome back!")
elif username == correct_username and password != correct_password:
    print("Wrong password. Try again.")
else:
    print("Username not found.")
Enter fullscreen mode Exit fullscreen mode

Output:

Wrong password. Try again.
Enter fullscreen mode Exit fullscreen mode

Change the password to "python2024" and run again. Now try a completely wrong username. See how each path behaves differently.


Three Mistakes That Will Definitely Happen

Mistake 1: Using = instead of == inside a condition

age = 25

if age = 18:       # wrong
    print("Adult")
Enter fullscreen mode Exit fullscreen mode

Error:

SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

Inside an if condition, you almost never want =. You want == to compare.

if age == 18:      # correct
    print("Exactly 18")
Enter fullscreen mode Exit fullscreen mode

Mistake 2: Missing the colon

if age >= 18      # wrong, no colon
    print("Adult")
Enter fullscreen mode Exit fullscreen mode

Error:

SyntaxError: expected ':'
Enter fullscreen mode Exit fullscreen mode

Every if, elif, and else line ends with a colon. No exceptions.

Mistake 3: Wrong indentation

if age >= 18:
print("Adult")      # wrong, not indented
Enter fullscreen mode Exit fullscreen mode

Error:

IndentationError: expected an indented block after 'if' statement
Enter fullscreen mode Exit fullscreen mode

The code inside an if block must be indented. Four spaces is the standard. VS Code will do this automatically when you press enter after a colon.


Try This Yourself

Create a file called decisions.py.

Write a program that acts as a basic ticket pricing system. Store a person's age in a variable. Then print their ticket price based on these rules:

  • Under 5 years old: free
  • 5 to 12 years old: half price (pick any price you want)
  • 13 to 17: student price (a bit more)
  • 18 to 64: full adult price
  • 65 and above: senior discount

Print a message that says the category and the price. Something like "Child ticket: 200 rupees" or whatever makes sense.

Then change the age variable to five different ages and make sure each one prints the right thing.

Hint: you need elif for this. Multiple conditions, in the right order.


What's Next

Your code can make decisions now. But right now it only makes that decision once. What if you want it to repeat something a hundred times without writing it a hundred times? That's what loops do, and that's the next post.

Top comments (0)