Skip to content
Home » Nonassociative Operators in Python

Nonassociative Operators in Python

Spread the love

In the previous article we were talking about operator associativity. Also, in one of my previous articles we were talking about the precedence of operators. In this article we’ll be talking about nonassociative operators.

Here’s the video version of this article:

Some operators that are on the same level of precedence are nonassociative. The assignment and comparison operators belong in this group.

Assignment Operators

Let’s have a look at the assignment operators first. The basic assignment operator works in such a way that the last value is assigned to all the variables on the way:

 >>> a = 5
 >>> b = 3 
 >>> c = 4
 >>> a = b = c
 >>> a
 4
  
 >>> b
 4
  
 >>> c
 4 

If we try to do something similar with an augmented assignment operator, we’ll get an error:

 >>> a, b, c = 5, 3, 4
 >>> a = b += c
   File "<stdin>", line 1
     a = b += c
            ^
 SyntaxError: invalid syntax 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Comparison Operators

Now let’s have a look at the comparison operators. We can chain comparison operators like in math. So we can write:

 >>> 2 < 4 < 7
 True

instead of its equivalent:

 >>> 2 < 4 and 4 < 7
 True 

It works the same for the greater than operator:

 >>> 8 > 6 > 3
 True 

which is an equivalent of this:

 >>> 8 > 6 and 6 > 3
 True 

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

We can combine the operators in quite interesting ways. They’re just a shorthand for the full form with the logical and operator. So instead of writing 6 < 8 and 8 == 8, we can write:

 >>> 6 < 8 == 8
 True 

Here’s a more complex example:

 >>> 3 == 3 < 6 < 8 == 8 < 10
 True

But we can also use other combinations, which are not considered correct in math:

 >>> 2 < 4 > 3     # same as 2 < 4 and 4 > 3
 True
  
 >>> 2 > 1 < 5     # same as 2 > 1 and 1 < 5
 True 

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply