Arithmetic, Logical, And Comparison Operators in Python (vs JavaScript)

First installment of Python For JavaScript Developers, a series of side-by-side between Python and JavaScript. In this episode: arithmetic, logical, and comparison operators in Python (vs JavaScript).

Python For JavaScript Developers: Arithmetic And Comparison

JavaScript is my bread and butter, but I don’t dislike other programming languages, at all. In fact I always had a crush for Python which I used over the years ranging from scripts to API applications with Flask and Django.

This series is a hitchhiker guide to Python for JavaScript developers, wrote as a reference while training other fellow devs, and as a note for my future self. Enjoy!

In this episode:

  • Arithmetic operators
  • Increment and decrement
  • Comparison operators
  • Logical operators

Requirements

To follow along you need at least a basic understanding of JavaScript and its quirks. This series is not an exhaustive guide to both languages, rather, a 10.000 feet comparison between them.

You can try the code examples for JavaScript in a browsers’s console or in the Node.js REPL. For Python you can use the Python REPL. Every time you see “>>>” in the code examples, that’s the Python REPL.

The complete series

Missed an episode? Here we go:

Arithmetic operators in Python and JavaScript

Both Python and JavaScript share more or less the same arithmetic operators. But in addition (no pun intended) to the division operator, Python has also a floor division operator.

OPERATORPYTHONJAVASCRIPT
addition++
subtraction
multiplication**
exponent****
division//
floor division//n/a
modulo%%

Floor division returns the integer quotient of the division between two numbers. Consider the following example in Python:

>>> 89 / 4

# Output: 22.25

To get an integer instead of a float we can use floor division . (Worth nothing for beginners that // in JavaScript is a comment):

>>> 89 // 4

# Output: 22

To replicate the same result in JavaScript you would use Math.floor:

Math.floor(89 / 4)

// Output: 22

Python’s arithmetic operators do not operate exclusively on numbers. For example you can use multiplication on strings to repeat a pattern:

>>> "a" * 9

# Output: 'aaaaaaaaa'

Or addition as well to concatenate simple strings:

>>> "a" + "aa"

# Output: 'aaa'

For everything else Python raises a TypeError. That means you cannot sum a number and a string together:

>>> "a" + 9

# TypeError: can only concatenate str (not "int") to str

Nor divide them (besides making no sense):

>>> "a" / 9

# TypeError: unsupported operand type(s) for /: 'str' and 'int'

On this front JavaScript is a complete mess in the eye of an external observer because of the infamous type coercion. Not only JavaScript’s arithmetic operators are free to convert numbers to string:

"a" + 9

// Output: "a9"

They do not raise any error in case of invalid arithmetic operations:

"a" / 9

// Output: NaN

Instead we get NaN, a special JavaScript value resulting from invalid arithmetic operations, difficulty to deal with, until ECMAScript 2015 Number.isNaN.

Increment and decrement operators in Python and JavaScript

OPERATORPYTHONJAVASCRIPT
incrementn/a++
decrementn/a

JavaScript has an increment and a decrement operator. Both can be used prefix (before the number):

var a = 34;
++a

or postfix (after the number):

var a = 34;
a++

In the first case (prefix), the operator increments the number and returns the new number:

var a = 34;
++a
// returns 35

In the second case (postfix), the operator increments the number, but returns the original number:

var a = 34;
a++
// returns 34
// increments to 35

The same rules are true for the decrement operator.

In Python instead there is no such thing as a decrement/increment operator. Rather you have to use an assignment operator. Here’s an increment assignment in Python:

>>> a = 34
>>> a += 1
# a is now 35

And here’s a decrement assignment:

>>> a = 35
>>> a -= 2
# a is now 33

JavaScript has assignment operators as well.

Comparison operators in Python and JavaScript

JavaScript and Python have the same comparison operators, except for the triple equal, emblematic of JavaScript’s weird coercion rules.

There is a huge literature on that topic, I won’t bother you too much. You can read more on the quintessential “You Don’t Know JS – Types and Coercion” or from my Little JavaScript book.

Here are Python and JavaScript comparison operators side by side:

OPERATORPYTHONJAVASCRIPT
greater than>>
less than<<
greater or equal than>=>=
less or equal than<=<=
equal====
strict (triple) equaln/a===
not equal!==!==

To be precise Python has also the is operator (not discussed here) which for me falls more in the identity operators family.

What matters here is that Python is predictable when comparing values:

>>> 9 == "9"

# Output: False

JavaScript on the other hand performs a conversion every time the “weak comparison” operator is involved:

9 == "9"

// Output: true

Here the first operator 9 is converted to a string right before the comparison. To avoid the conversion you must use the “strict comparison operator“, also called triple-equal:

9 === "9"

// Output: false

Logical operators in Python and JavaScript

Now that we talked about arithmetic and comparison operators let’s see their companions: logical operators. Oh, my friend, I can still remember boolean algebra in high school. Do you?

Here are the most common logical operators for Python and JavaScript:

OPERATORPYTHONJAVASCRIPT
logical andand&&
logical oror||
logical negationnot!

Logical operators are useful when you want to do (or not to do) something in your code depending on the outcome of an expression. Suppose we want to print “I am cool” only if 2019 is greater than 1900. Here’s how you’ll do it with the logical operator and in Python:

>>> 2019 > 1900 and print("I am cool")

# Output: "I am cool"

and means: do the stuff on the right only if the stuff on the left is true. The same logic in JavaScript maps to:

2019 > 1900 && console.log("I am cool")

The or logical operator works the other way around. or means: do the stuff on the right only if the stuff on the left is false. Here’s an example in Python:

>>> 2019 > 1900 or print("I am cool")

# Output: True

The result is simply “True” because 2019 is greater than 1900 so the evaluation stops there. Here’s the same logic in JavaScript:

2019 > 1900 || console.log("I am cool")

Last but not least there is logical negation, useful when you want to flip the result of an expression. For example we can print “I am cool” even if a given expression on the left is false. How? With the not operator in Python:

>>> not 2019 > 151900 and print("I am cool")

# Output: "I am cool"

2019 is clearly smaller than 151900, but logical not flips the result, so the right expression is still evaluated. The following example should be more simple to grasp:

>>> not False and print("I am cool")

# Output: "I am cool"

Logical negation in JavaScript uses an exclamation mark instead:

!false && console.log("I am cool")

Wrapping up

Python and JavaScript are not so different after all, aren’t they? The main distinction, and it wasn’t a surprise, is JavaScript’s looseness when comparing values with the double equal.

Also, Python is less forgiving and there is no way to sum a number to a string, even by accident, let alone changing numbers. Python as the same arithmetic operators as JavaScript, with the addition of a floor division operator.

For the most common logical operators Python has “and”, “or”, and “not”, a more descriptive syntax compared to JavaScript’s “&&”, “||” and “!”.

Thanks for reading and stay tuned for more!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.