Sunday, September 15, 2019

Python tutorial 4 | Comparison Operators

This is the fourth of Python Tutorials for Beginners. You can see all the Python tutorials in this blog here. This Python beginner tutorial explains comparison operations in Python programming with multiple examples. Please view my Python video tutorial 4 or read on...

You can use Python comparison operators when you write conditions in Python if statement or Python while loop statement. In Python programming language, the comparison operators include equal to, not equal to, less than, less than or equal to, greater than and greater than or equal to. The result of any Python comparison operation is a True or False value.

A single Python condition may contain different comparison operators but all comparison operators in Python have the same priority. This means that there is no operator precedence.
Now, let us see these comparison operators with examples.

You can try these Python commands at the Python prompt. Note that comments follow the # symbol (they are only for your understanding). Let us see number comparison, string comparison, Boolean comparison and multiple comparisons.
>>> 1 == 1               # this Python statement echoes the result, which is True
>>> 1 != 2              # echoes True because the two number values are not equal
>>> 1 < 2             # echoes True because the left value is less than the right value
>>> 1 >= 2            # echoes False because the left value is not greater than or equal to the right value
>>> 1 + 2 == 3              # the priority of Python arithmetic operators is higher than comparison operators, so 1 and 2 are added first and then compared with the value (operand) on the right, resulting in True
>>> 1 < 2 < 3             # this is a multiple comparison, which echoes True because 1 is less than 2 and 2 is less than 3
>>> x = 'Hi'
>>> x == 'Hello'             # echoes False because the two string values are different
>>> 'a' <= 'A'             # echoes False because the character 'a' is greater than the character 'A' in the character set
>>> True == False            # echoes False because the two Boolean values are not equal
>>> True != False            # echoes True because the two Boolean values are not equal

You can see the comparison operators in action in my Python video tutorial 4. Thank you.

No comments:

Post a Comment