PythonProgramming Basics

Python Conditionals & Logical Operators: A Complete Guide

TT
TopicTrick
Python Conditionals & Logical Operators: A Complete Guide

Introduction to Conditional Statements

In programming, decision-making is essential. Conditional Statements allow your code to branch into different paths based on whether a specific condition is met.

Whether you're checking if a number is even or validating a user password, these statements are the backbone of program logic.


Relational Operators

Before making decisions, we need to compare values. Relational Operators are used to test the relationship between two entities.

OperatorNameExampleResult
==Equal5 == 5True
!=Not Equal5 != 3True
>Greater Than5 > 10False
<Less Than5 < 10True
>=Greater or Equal5 >= 5True
<=Less or Equal5 <= 2False

Python Trick: Chained Comparisons

In Python, you can chain comparisons! Instead of `(x < y and y < z)`, you can simply write `x < y < z` for cleaner, more readable code.


    1. The if Statement

    The if statement evaluates an expression. If it's True, the indented code block below it executes.

    python
    1age = 20 2if age >= 18: 3 print("You are an adult.")

    2. Using if-else for Alternatives

    What if the condition is False? We use else to provide an alternative path.

    python
    1score = 45 2if score >= 50: 3 print("You passed!") 4else: 5 print("Try again next time.")

    3. Multiple Conditions: if-elif-else

    When you have more than two possible outcomes, use elif (short for else if).

    python
    1temperature = 25 2 3if temperature > 30: 4 print("It's a hot day.") 5elif 20 <= temperature <= 30: 6 print("The weather is perfect.") 7else: 8 print("It's a bit chilly.")

    4. Logical Operators: and, or, not

    Logical operators combine multiple conditions into a single Boolean value.

    Truth Table Reference

    Condition ACondition BA and BA or Bnot A
    TrueTrueTrueTrueFalse
    TrueFalseFalseTrueFalse
    FalseTrueFalseTrueTrue
    FalseFalseFalseFalseTrue
    python
    1has_permission = True 2is_logged_in = True 3 4if has_permission and is_logged_in: 5 print("Welcome to the dashboard!")

    5. The is Operator vs ==

    Many beginners confuse is with ==.

    • == checks for Equality: Do these variables have the same value?
    • is checks for Identity: Do these variables point to the same memory location?
    python
    1list1 = [1, 2, 3] 2list2 = [1, 2, 3] 3list3 = list1 4 5print(list1 == list2) # True (Same values) 6print(list1 is list2) # False (Different objects in memory) 7print(list1 is list3) # True (Point to the exact same object)

    Falsy Values in Python

    In Python, several values are considered Falsy, meaning they evaluate to False in a conditional context.

    CategoryFalsy Values
    ConstantsNone, False
    Numbers0, 0.0, 0j
    Sequences'' (empty string), [] (empty list), () (empty tuple)
    Mappings{} (empty dictionary)
    python
    1username = "" # Empty strings are Falsy 2if not username: 3 print("Username cannot be empty!")

    Conclusion

    Understanding conditional flow and logical operators is the key to writing smart, reactive Python applications. Combine these with Loops to create robust logic for your projects!

    What's Next?

    Now that you can make decisions in code, it's time to explore Python Functions to organize your logic into reusable blocks.