Your First Steps in Python: A Beginner to Intermediate Guide

Logical Operators: Combining Conditions for Smarter Decisions

Section 8

Variables and Operators: Storing and Manipulating Data

Your First Steps in Python: A Beginner to Intermediate GuideVariables and Operators: Storing and Manipulating Data

Now that we understand how to create conditions using comparison operators, it's time to learn how to combine these conditions to make even more sophisticated decisions. This is where logical operators come into play. They allow us to build complex expressions from simpler ones, leading to more nuanced and powerful program logic.

Python provides three primary logical operators: and, or, and not. Each has a distinct role in evaluating the truthiness of combined conditions.

The and operator is used when you need both conditions to be true for the entire expression to be true. Think of it as a requirement for everything to align. If even one of the conditions is false, the whole expression evaluates to false.

is_sunny = True
is_warm = True

if is_sunny and is_warm:
    print("It's a perfect day for a picnic!")
else:
    print("Maybe another day.")

Let's see how and works with different scenarios:

  • True and True evaluates to True.
  • True and False evaluates to False.
  • False and True evaluates to False.
  • False and False evaluates to False.
graph TD;
    A[Condition 1];
    B[Condition 2];
    C{AND Operator};
    D[Result is True ONLY IF both A and B are True];
    A --> C;
    B --> C;
    C --> D;

The or operator, on the other hand, is more forgiving. The entire expression is true if at least one of the conditions is true. It only evaluates to false if both conditions are false. This is useful when you have alternative options or requirements.

has_coupon = False
is_member = True

if has_coupon or is_member:
    print("You get a discount!")
else:
    print("No discount for you this time.")
チャプターへ戻る