DEV Community

Cover image for Python Operators & Conditionals
Alex Murithi
Alex Murithi

Posted on

Python Operators & Conditionals

comparison operators and conditional statements (if, elif, else)

i. Comparison Operators - Checking Values in Python
Comparison operators are used to compare two values. They always return a Boolean result (True or False). This is useful when making decisions in code.

age = 20
score = 75

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

Output

True
False
True
True
False
True
False
Enter fullscreen mode Exit fullscreen mode

ii. Comparing Strings - Case Sensitivity Matters
String comparisons check if two text values are equal. Python is case-sensitive, so "Data Engineering" is not equal to "data Engineering".

track = "Data Engineering"

print(track == "Data Engineering")
print(track == "data Engineering")
print(track == "Data Science")
print(track != "Data Science")
Enter fullscreen mode Exit fullscreen mode

Output

True
False
False
True
Enter fullscreen mode Exit fullscreen mode

iii. Alphabetical Comparison - Order of Characters
Strings can also be compared alphabetically. Python uses Unicode values, so "A" is less than "C".

print("Amina" < "Collins")   # True, A comes before C
print("Nairobi" == "nairobi") # False, case-sensitive
Enter fullscreen mode Exit fullscreen mode

Output

True
False
Enter fullscreen mode Exit fullscreen mode

iv. Basic if Statement - Single Condition Check
An if statement runs code only when the condition is true. If the condition is false, the block is skipped.

score = 55

if score >= 50:
    print("You passed")      
print("Thank you for taking the test")
Enter fullscreen mode Exit fullscreen mode

Output

You passed
Thank you for taking the test
Enter fullscreen mode Exit fullscreen mode

v. if with else - Two Possible Paths
The else block runs when the if condition is false, giving two possible outcomes.

score = 45

if score >= 50:
    print("Pass well done")
else:
    print("FAIL - Please try again")

print(f"Your Score was {score}")
Enter fullscreen mode Exit fullscreen mode

Output

FAIL - Please try again
Your Score was 45
Enter fullscreen mode Exit fullscreen mode

vi. if-elif-else - Multiple Conditions
elif allows checking multiple conditions in sequence. Order matters — the first true condition is executed.

score = 72

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 - Failed")
Enter fullscreen mode Exit fullscreen mode

Output

Grade B - Good
Enter fullscreen mode Exit fullscreen mode

Matatu Ticket Pricing- Example
Conditionals can model real-world systems like fare calculation.

distance = 12

if distance <= 5:
    fare = 30
elif distance <= 15:
    fare = 50
elif distance <= 30:
    fare = 80
else:
    fare = 120

print("=========MATATU FARE========")
print(f"Distance: {distance}km | Fare Ksh{fare}")
print("----------------------------")
Enter fullscreen mode Exit fullscreen mode

Output

text
=========MATATU FARE========
Distance: 12km | Fare Ksh50
----------------------------
Enter fullscreen mode Exit fullscreen mode

vii. Logical Operators - Combining Conditions
Logical operators (and, or, not) let us combine multiple conditions.

  • Using and - Both Must Be True
age = 18
has_id = "yes"

if age >= 18 and has_id == "yes":
    print("Access granted - Welcome")
else:
    print("Access denied")
Enter fullscreen mode Exit fullscreen mode

Output

text
Access granted - Welcome
Enter fullscreen mode Exit fullscreen mode
  • Using or - At Least One Must Be True
is_student = "yes"
is_senior = "no"

if is_student == "yes" or is_senior == "yes":
    print("Discount applied - 25% off")
else:
    print("No discount")
Enter fullscreen mode Exit fullscreen mode

Output

text
Discount applied - 25% off
Enter fullscreen mode Exit fullscreen mode

Example: Banking - Transaction Limits
Different account types have different limits. Conditionals enforce these rules.

account = "basic"
amount = 80000

if account == "basic" and amount <= 70000:
    print("Transaction Approved")
elif account == "basic" and amount > 70000:
    print("Limit Exceeded for basic account")
elif account == "premium" and amount <= 300000:
    print("Transaction Approved")
else:
    print("Limit exceeded for premium account (max Ksh 300,000)")
Enter fullscreen mode Exit fullscreen mode

Output

Limit Exceeded for basic account
Enter fullscreen mode Exit fullscreen mode

viii. Nested if - Step-by-Step Checks
Nested if allows deeper checks when one condition depends on another.

username = "admin"

if username == "admin":
    password = "kenya2025"
    if password == "kenya2025":
        print("Welcome admin")
    else:
        print("Incorrect password")
else:
    print("User not found")
Enter fullscreen mode Exit fullscreen mode

Output

Welcome admin
Enter fullscreen mode Exit fullscreen mode

Example: Track Enrolled - elif for Alternatives
elif is useful when there are multiple possible paths.

track = "DE"

if track == "DS":
    print("Your next course: Pandas and Numpy")
elif track == "DE":
    print("Your next course: Kafka and Airflow")
else:
    print("Unknown track")
Enter fullscreen mode Exit fullscreen mode

Output

Your next course: Kafka and Airflow
Enter fullscreen mode Exit fullscreen mode

Example: Laptop process - Nested Decision
Here, the second question depends on the first answer.

has_laptop = "yes"
os_type = "Windows"

if has_laptop == "yes":
    if os_type == "Windows":
        print("Install python from python.org")
    else:
        print("Python may already be installed - check with python3 --version")   
else:
    print("Please borrow a laptop for this session")
Enter fullscreen mode Exit fullscreen mode

Output

Install python from python.org
Enter fullscreen mode Exit fullscreen mode

Example: Loan Qualification - Multiple Nested Checks
This example combines several conditions to decide loan eligibility.

has_account = "yes"
months_in = 8
salary = 25000

if has_account == "yes":
    if months_in < 6:
        print("You need at least 6 months of account history")
    else:
        if salary < 20000:
            print("Minimum salary for a loan is Ksh 20000")
        else:
            print("Congratulations! You qualify for a loan")
else:
    print("Sorry, you do not have an account")
Enter fullscreen mode Exit fullscreen mode

Output

Congratulations! You qualify for a loan
Enter fullscreen mode Exit fullscreen mode

Conclusion

Comparison operators check values and relationships.

Conditionals (if, elif, else) control program flow.

Logical operators (and, or) combine conditions.

Nested if allows deeper decision-making.

Order of conditions matters - always put the most specific first.

Top comments (0)