DEV Community

Maureen Kipkosgei
Maureen Kipkosgei

Posted on

Making Decisions in Python: Operators and Conditional Logic

Every program eventually has to make a choice, charge tax or don't, grant access or deny it, show one message instead of another. Python makes these decisions using a small set of tools that work together: operators that compute or compare values, and if/else statements that act on the result. This article covers all of them, and how they combine to give your code the ability to respond differently depending on the situation.

Arithmetic Operators: Doing the Math

These are the operators you likely already recognize, plus a couple that are easy to overlook.

a, b = 7, 2

a + b   # 9  - addition
a - b   # 5  - subtraction
a * b   # 14 - multiplication
a / b   # 3.5 - division (always returns a float)
a // b  # 3  - floor division (drops the remainder)
a % b   # 1 - modulus (the remainder)
a ** b  # 49 - exponent ( 7 squared)
Enter fullscreen mode Exit fullscreen mode

// and % are the two operators that are forgotten. // is how you get a whole number (like splitting items evenly), and % is how you check things like even or odd, or wrap a value around a fixed range:

total_items = 23
items_per_box = 5

boxes = total_items // items_per_box  # 4 full boxes
leftover = total_items % items_per_box   # 3 items left over
Enter fullscreen mode Exit fullscreen mode

Comparison Operators: Asking Questions About Values

Comparison operators do not calculate a new value, they ask a yes/ no question and return True or False.

  • == - equal to
  • != - not equal to
  • > - greater than
  • < - less than
  • >= - greater than or equal to
  • <= - less than or equal to
x, y = 10, 20
x == y       # False   
x != y       # True
x > y        # False
x < y        # True
x >= 10      # True 
x <= 5       # False
Enter fullscreen mode Exit fullscreen mode

A common early mistake is confusing =(assignment) with ==(comparison):

x = 5   # assigns 5 to x
x == 5  # asks: is x equal to 5? True
Enter fullscreen mode Exit fullscreen mode

This distinction matters because it's the difference between setting a value and checking one, mixing them up is one of the most common early bugs in any language, not just Python.

Logical Operators: Combining Conditions

Logical operators let you combine multiple True/ False conditions into one.

  • and - returns true only if both conditions on either side of it are true. If one condition is false the whole thing becomes false. Useful for requirements that must all be met (old enough and has id).
age = 20
has_id = True

age >= 18 and has_id # True - both conditions are true
age <= 18 and has_id # False - both conditions are not true.
Enter fullscreen mode Exit fullscreen mode
  • or - returns true if at least one of the conditions is true. Returns false if every condition is false. Useful for alternative paths to the same outcome ( has a membership card or is a first-time visitor).
is_student = True
is_senior = False

is_student or is_senior # True - at least one condition is true
Enter fullscreen mode Exit fullscreen mode
  • not - reverses the result. It turns true into false and vice versa. Useful for checking the absence of something.
is_raining = False

not is_raining # True - flips False to True (or vice versa)
Enter fullscreen mode Exit fullscreen mode

Combining the operators:

is_weekend = True
is_holiday = False
has_ticket True

can_enter = (is_weekend or is_holiday) and has_ticket
print(can_enter)   # True
Enter fullscreen mode Exit fullscreen mode

If Else Statements: Acting on the Result

Operators produce True or False. if statements are what you actually do with that answer.
The if-else statement is used to execute one block of code when a condition is True and another block when the condition is False. It helps programs make decisions based on different conditions.

Example:

score = 75

if score >= 50:
    print("Congragulations! You passed")
else:
    print("Sorry! You did not pass. Try again")
Enter fullscreen mode Exit fullscreen mode
# Output

Congragulations! You passed
Enter fullscreen mode Exit fullscreen mode

When there are more than two possible outcomes, elif ("else if") lets you check additional conditions in order:

score = 75 

if score >= 80:
    print("GRADE A - Excellent")
elif score >= 70:
    print("GRADE B - Good")
elif score >= 60:
    print("GRADE C - Average")
elif score >= 50:
    print("GRADE D - Below Average")
else:
    print("GRADE F - Fail")
Enter fullscreen mode Exit fullscreen mode
# Output
GRADE B - Good
Enter fullscreen mode Exit fullscreen mode

How this works: Python checks each condition top to bottom and stops at the first one that is True. Since 75 >= 80 is False, it moves to the next condition, 75 >= 70 is True, so grade becomes B and every condition after that is skipped.

Order Matters in Condition Statements

score = 75

if score >= 50:
    print("GRADE D - Average")
elif score >= 70:
    print("GRADE B - Good")
else: 
    print("GRADE F - Fail")
Enter fullscreen mode Exit fullscreen mode
# Output
GRADE D - Average
Enter fullscreen mode Exit fullscreen mode

Here, grade ends up as D, not B because 75 >= 50 is checked first, matches, and the rest is skipped.

Nesting Conditions

if statements can live inside other if statements, which is useful when a decision only makes sense after another one has already been settled.

Basic nested if example:

passed_test = True
age = 16

if passed_test:
    # This inner check only happens if passed_test is True
    if age >= 18:
        print("You can get your driving license!")
    else:
        print("You passed, but you are too young to drive.")
else:
    print("You need to pass the test first.")
Enter fullscreen mode Exit fullscreen mode
# Output
You passed, but you are too young to drive.
Enter fullscreen mode Exit fullscreen mode

Multiple Levels nesting:

username = "admin"
password = "Python145!"
two_factor_code = 1287

if username == "admin":
    if password == "Python145!":
        if two_factor_code == 1287:
            print("Welcome admin.")
        else: 
            print("Invalid 2FA code.")
    else:
        print("Incorrect Password.")
else:
    print("User not found.")
Enter fullscreen mode Exit fullscreen mode

You can frequently flatten nested if statements by combining conditions with the logical and operator.

Example:

passed_test = True
age = 16

if passed_test and age >= 18:
    print("You can get your driving license!")
elif passed_test and age < 18:
    print("You passed, but you are too young to drive.")
else:
     print("You need to pass the test first.")
Enter fullscreen mode Exit fullscreen mode

Practical Example

Here is an example combining operators and conditionals.

account = input("Enter your account type (basic/premium): ")
amount = int(input("Enter amount to send (Ksh): "))

if account == "basic" and amount <= 70000:
    print("Transaction approved")
elif account == "basic" and amount > 70000:
    print("Limit exceeded for basic account(max Ksh 70000)")
elif account == "premium" and amount <= 300000:
    print("Transcation approved")
elif account == "premium" and amount > 300000:
    print("Limit exceed for premium account (max Ksh 300000)")
else:
    print("Unknown account type")
Enter fullscreen mode Exit fullscreen mode

Output

Enter your account type (basic/premium): basic
Enter amount to send (Ksh): 100000
Limit exceeded for basic account(max Ksh 70000)
Enter fullscreen mode Exit fullscreen mode

Conclusion
Operators and conditionals are two halves of the same skill: operators produce an answer, and if/else decides what to do with it. Nearly every piece of interesting program behavior: validation, pricing, access control, game rules comes down to combinations of these tools.

Top comments (0)