DEV Community

Cover image for Python Operators and Conditionals: Teaching Your Program to Make Decisions!!
Neema Kirui
Neema Kirui

Posted on

Python Operators and Conditionals: Teaching Your Program to Make Decisions!!

If you've been following along, you already know how to store a value and get information in and out of a program. That's still a program that just does one fixed thing, though. Operators are how Python compares and combines values, and conditionals are how it uses those comparisons to actually choose what to do next. Put together, they're the first real building block of a program that behaves differently depending on the situation.

1. Arithmetic Operators: The Math You Already Know, Plus Two You Might Not

Most of these look exactly like the math you already know:

Operator Meaning Example Result
+ Add 5 + 2 7
- Subtract 5 - 2 3
* Multiply 5 * 2 10
/ Divide 5 / 2 2.5
// Floor division 5 // 2 2
% Modulus (remainder) 5 % 2 1
** Exponent (power) 5 ** 2 25

// and % are the two that usually feel new. Floor division divides and throws away anything after the decimal point, and modulus gives you what's left over after that division. They show up together constantly, splitting something evenly and figuring out the remainder:

total_items = 17
per_box = 5

boxes = total_items // per_box   # 3 full boxes
leftover = total_items % per_box  # 2 items left over

print(f"{boxes} full boxes, {leftover} items left over")
Enter fullscreen mode Exit fullscreen mode

GOOD TO KNOW
% is also the easiest way to check if a number is even or odd. number % 2 == 0 is true for even numbers, since dividing an even number by 2 always leaves a remainder of zero.

2. Comparison Operators: Questions With Only Two Possible Answers

Every comparison in Python returns exactly one of two things: True or False. Nothing in between, nothing partial.

age = 20
score = 75

print(age == 20)    # True  (equal to?)
print(age == 25)    # False
print(age != 18)     # True  (not equal to?)
print(score > 70)   # True
print(score < 50)   # False
print(score >= 75)  # True
print(score <= 74)  # False
Enter fullscreen mode Exit fullscreen mode

Each line is just a yes-or-no question that Python answers instantly. age == 20 is asking "is age equal to 20?", not assigning anything, which is exactly where the most common beginner slip happens.

COMMON BUG
= assigns a value. == asks a question. if score = 75 is not the same thing as if score == 75, and mixing them up inside a condition is one of the most common early mistakes there is. Python usually stops you with a clear error if you try it, so treat that error as a hint, not a disaster.

Strings can be compared too, and it's worth knowing this catches people off guard the first time: comparisons are case-sensitive.

print("Alice" == "alice")   # False, capital A isn't the same as lowercase a
print("A" < "B")            # True, alphabetical order works here too
Enter fullscreen mode Exit fullscreen mode

3. Logical Operators: Combining More Than One Condition

and, or, and not let you combine multiple conditions into a single decision instead of nesting a pile of separate if statements.

account_type = "basic"
amount = 85000

if account_type == "basic" and amount <= 70000:
    print("Transaction approved")
elif account_type == "basic" and amount > 70000:
    print("Limit exceeded for basic account (max Ksh 70,000)")
elif account_type == "premium" and amount <= 300000:
    print("Transaction approved")
else:
    print("Check account rules")
Enter fullscreen mode Exit fullscreen mode

and needs both sides to be true before the whole condition counts as true. Trace it through: account_type == "basic" is true, but amount <= 70000 is false, since 85,000 is well over that. Both need to hold for the first line to match, so Python moves down to the next check instead.

WHY IT MATTERS
and requires everything to be true. or only needs one side to be true. not flips whatever comes after it, not True becomes False. This is real logic banks and apps actually run on, "approve this transaction only if the account type matches AND the amount is within its limit" is exactly the kind of rule and was built for.

4. if / elif / else: Turning Questions Into Actions

Comparisons and logical operators are how you ask a question. if, elif, and else are how your program actually acts on the answer.

score = 68

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

Python checks each condition top to bottom and stops at the very first one that's true. score = 68 fails the first check (not 80 or above), matches the second (60 or above), and never even evaluates the rest. Order matters a lot here, if you accidentally put the loosest condition first, everything below it becomes unreachable.

5. Putting It Together: A Loan Eligibility Checker

Here's everything from this post, arithmetic, comparisons, logical operators, and conditionals, working together in one small program.

income = float(input("Enter your monthly income (Ksh): "))
existing_debt = float(input("Enter your existing monthly debt payments (Ksh): "))
requested_loan = float(input("Enter requested monthly loan payment (Ksh): "))

total_debt = existing_debt + requested_loan
debt_ratio = total_debt / income

print(f"\nYour debt-to-income ratio would be {debt_ratio:.2%}")

if debt_ratio <= 0.3 and income >= 20000:
    print("Loan approved.")
elif debt_ratio <= 0.3 and income < 20000:
    print("Loan denied: income below minimum threshold.")
elif debt_ratio > 0.3:
    print("Loan denied: debt-to-income ratio too high.")
else:
    print("Unable to process application.")
Enter fullscreen mode Exit fullscreen mode

That debt_ratio <= 0.3 check is a comparison, debt_ratio <= 0.3 and income >= 20000 is a logical combination of two comparisons, and total_debt / income is plain arithmetic feeding directly into the decision. The elif chain is doing exactly what a loan officer's rulebook would do, checking conditions in order and applying whichever one matches first.

Why This Part Matters More Than It Looks Like It Does

Every "smart" behaviour you've ever seen in an app, a form rejecting an invalid entry, a discount applying automatically, a login failing on the wrong password, is some combination of an operator asking a question and a conditional deciding what to do with the answer. There's no deeper magic underneath it.

This is also usually where people first genuinely feel like they're programming, rather than just typing instructions in a straight line. That feeling is worth paying attention to. Comparisons and conditionals are the first moment your code actually reacts to the world instead of just repeating a script, and almost everything more advanced you'll build later is this same idea, asked more times, in more combinations.

Top comments (0)