Comparison Operators#

Relational operators, also called comparison operators, allow us to run True/False tests on specific conditions, focusing on the relationship(s) between two or more values.

Relational operators or comparison operators in Python:

NameSyntaxExampleDescription
Equal==x == yTests if values are equal
Not equal!=x != yTests if values are not equal
Greater than>x > yTests is a value is greater than another
Less than<x < yTests is a value is less than another
Greater than or equal to>=x >= yTests if a value is greater than or equal to another
Less than or equal to<=x <= yTests if a value is less than or equal to another

Boolean Logic#

We’ve talked previously about the Boolean data type. The underlying True/False logic lets us test for specific conditions and then specify how our code will execute based on the truth value for those conditional statements.

  • “You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer” (W3Schools, Python Booleans)

Boolean Logic & Comparison Operator Examples#

We can use comparison operators with a print() statement to test whether a particular statement is True or False.

A few Python examples:

print(4 == 5) # returns false
print(6 < 10) # returns true
# comparison operator using variables
x = 5
y = 6

print(x > y) # returns false

Comparison Operators & String Objects#

We can probably make intuitive sense of how these comparison operators would work for numeric values. But what about text characters or string objects?

Most programming languages treat the 26 characters in the English-language alphabet (a-z) as sequential values, where a is less than b, which is less than c, etc.

When working with string objects that represent words or characters, comparison operators indicate positionality in the English-language alphabet.

A few examples in Python:

print("apple" > "banana") # returns false
print("Ohio State" > "Notre Dame") # returns true

Comprehension Check#

Clipboard icon Comparison Operators Comprehension Check

Application#

Q11: Write a program that uses each of Python’s comparison operators (==, !=, >, <, >=, <=) to compare two numeric values. Answer to this question includes program + comments that document process and explain your code.

Outline for this program:

# first numeric value

# second numeric value

# equal

# not equal

# greater than

# less than

# greater than or equal to

# less than or equal to

Q12: Write a program that uses each of Python’s comparison operators (==, !=, >, <, >=, <=) to compare two string objects. Answer to this question includes program + comments that document process and explain your code.

Outline for this program:

# first string object

# second string object

# equal

# not equal

# greater than

# less than

# greater than or equal to

# less than or equal to