It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Logical Expressions and Comparison Operators

In Python, logical expressions are used to compare values and make decisions based on the result (True or False). These expressions are fundamental when writing if statements or controlling loops.


What is a Logical Expression?

A logical expression (also called a Boolean expression) is an expression that evaluates to either True or False.

5 > 3       # True
10 == 10    # True
4 != 2      # True
7 < 1       # False

Comparison Operators

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 3 != 4 True
> Greater than 7 > 2 True
< Less than 1 < 5 True
>= Greater than or equal 8 >= 8 True
<= Less than or equal 6 <= 7 True

These operators help compare numbers, strings, and even lists in some cases.

Combining Conditions: and, or, not

You can combine multiple logical expressions using logical operators:

and

Returns True only if both expressions are True

x = 10
x > 5 and x < 20   # True
x > 5 and x < 9    # False

or

Returns True if at least one expression is True.

x = 10
x < 5 or x == 10   # True
x < 5 or x > 20    # False

not

Flips the result of a logical expression.

not True   # False
not (5 > 3)  # False

Example Use Case

age = 16
if age >= 13 and age <= 19:
    print("You're a teenager!")

This checks two conditions with and. Both must be true for the message to print.

Exercise: Try It Yourself!

  1. Write expressions for the following and print the result:
    • Is 5 equal to 5?
    • Is 10 not equal to 9?
    • Is 4 greater than or equal to 6?
    • Is 7 less than 10 or 15 less than 10?
    • Is the opposite of 5 < 2?
  2. What will this code output?
    x = 12
    if x > 10 and x % 2 == 0:
    print("x is greater than 10 and even")