Python language basics 9: relational operators
March 22, 2015 1 Comment
Introduction
In the previous post we looked at how to assign nulls to a variable using the None keyword. In this post we’ll look at Python’s relational operators. These are operators that help us compare two values.
Those of you who have experience with other object-oriented languages like C# or Java can safely skip this post. The relational operators are the same in Python: ==, !=, ,=.
Relational operators
You’ll be familiar with most of them from the maths classes:
- == : is equal to
- != : is not equal to
- < : less than
- > : more than
- <= : less than or equal to
- >= : greater than or equal to
The first two may look strange at first. We’ve already seen the operator that most people recognise as equality: ‘=’. However, we didn’t use it to compare two values but to assign a value to an operator. Hence ‘=’ can be viewed as the assignment operator and can be read as “becomes equal to”. E.g. x = 5 means “x becomes equal to 5” or “x is assigned the value of 5”.
The equality operator in the mathematical sense is the double-equal sign ‘==’. It is negated by the exclamation point ‘!’, i.e. != . Here are a couple of examples:
print(5 == 6) print(5 != 6) print(10 == 10) print(3 < 5) print(3 <= 3) print(5 > 4) print(5 >= 5)
The statements print the following [boolean] states:
False
True
True
True
True
True
True
The distinction between the equality and the assignment variable seems to be quite universal across the most popular programming languages. JavaScript has both the double equality operator ‘==’ and the triple-equality operator ‘===’ which is read as “is strictly equal to”.
I’ve only been exposed to a single programming language where the equal sign ‘=’ can be used as equality and assignment operator: Visual Basic .NET. The double-equality operator is not recognised in that language.
Read all Python-related posts on this blog here.
Reblogged this on Brian By Experience.