Search⌘ K

Comparisons

Explore how to use comparison and logical operators to evaluate conditions and control decisions in Python. Understand the use of if, else, and elif statements to execute code based on different scenarios, mastering essential skills for Python programming.

Let’s talk about the following:

  • Comparison operators
  • Logical operators
  • Conditional statements

Comparison operators

Comparison operators allow us to compare two elements. These operators include the greater than, the less than, the equal to, and the not equal to operators.

Let’s try each of these with examples:

Python 3.5
print('3 > 4 : ', 3 > 4) # 3 greater than 4?
print('3 < 4 : ', 3 < 4) # 3 less than 4?
print('2 >= 2 : ',2 >= 2) # 2 greater or equal to 2?
print('3 <= 4 : ', 3 <= 4) # 3 less or equal to 4?
# == is different than =, which is assignment operator
print('1 == 1 : ', 1 == 1)
# We can compare strings using == operator
print("'Tom' == 'TOM' : ",'Tom' == 'TOM')
print("'Tom' == 'Jim' : ",'Tom' == 'Jim')
print("'Tom' == 'Tom' : ",'Tom' == 'Tom')
# Not equal
print("'Tom' != 'Tom' : ", 'Tom' != 'Tom' )

Logical operators

Logical operators combine multiple conditions using the and and or operators between conditions.

  • For the and operator,
...