Comparison Operators
Use a comparison operator to compare two values:
Comparison Operators Table
main.py
# Operator | Name | Example
# == | Equal | x == y
# != | Not equal | x != y
# > | Greater than | x > y
# < | Less than | x < y
# >= | Greater than or equal to | x >= y
# <= | Less than or equal to | x <= y
Examples
Each comparison gives back either True or False, depending on the outcome:
Example
Prompt
Write a Python program that sets x = 5 and y = 3, then prints the result of each comparison operator (==, !=, >, <, >=, <=) applied to x and y.
Output: complete Python program
main.py
x = 5
y = 3
print(x == y)
print(x != y)
print(x > y)
print(x < y)
print(x >= y)
print(x <= y)
Chaining Comparison Operators
In Python, comparison operators can be chained:
Example
Prompt
Write a Python program that sets x = 5, then demonstrates chaining comparison operators by printing 1 < x < 10 and the equivalent expression using "and".
Output: complete Python program
main.py
x = 5
print(1 < x < 10)
print(1 < x and x < 10)