Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

More Advanced Comparisons

Complex Conditional Statements

We can imagine programming scenarios in which we want to compare more than two values or evaluate multiple conditions as part of a conditional statement. We can do this using logical operators and complex conditional statements.

For example, 5 < 6 > 7 evaluates whether 5 is less than 6 and 6 is greater than 7. This statement would return False.

An example using strings: "apple" > "banana" < "blueberry" evaluates whether "apple" is greater than (or comes after) "banana" and whether "banana" is less than (or comes before) "blueberry". This statement would return False.

Python examples:

# an example that compares three integers
print(5 < 6 > 7) # returns false because 6 is not greater than 7
# an example that compares three strings
print("apple" > "banana" < "blueberry") # returns false because apple comes before or is less than banana

Logical Operators

We can also compare or relate multiple conditions using logical operators: and, or, not

For example, 5 < 6 and 6 < 7 evaluates whether 5 < 6 and 6 < 7 are true. This statement would return True.

Another example: 5 < 6 or 6 > 7 evaluates whether 5 < 6 or 6 > 7 is true. This statement would return True.

Logical operators in Python:

NameSyntaxExampleDescription
Andandx == y and y != zReturns True if both statements are true
Ororx != y or y == zReturns True if one of the statements is true
Notnotnot(x == y and y != z)Reverses the result, returns False if the result is true
# example using logical operators
print(5 < 6 and 6 < 7) # returns true because both statements are true
print(5 < 6 or 6 > 7) # returns true because at least one statement is true
print(not(5 < 6 and 6 < 7)) # returns false, inverse of initial true

Application

Q13: Write a program that uses Python’s comparison operators (==, !=, >, <, >=, <=) to compare at least three (3) 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

# third numeric value

# complex comparison statement

Q14: Write a program that uses Python’s comparison operators (==, !=, >, <, >=, <=) to compare at least three (3) 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

# third string object

# complex comparison statement