26.7. Calculations and Operators

Python supports the standard mathematical operators for its various data types, and they work pretty much the same as in other languages. The following tables outline the arithmetic operators available in Python.

Python Arithmetic Operators

OperatorUse
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
**Exponent
++???Legal in Python but doesn't act as in other languages. Instead because + is a unary prefix, ++x parses to +(+(x)), which for numbers results in x.

Although Python's primary assignment operator is the equal sign, Python supports a number of others, as shown in the following table. It is worth noting that Python supports multiple assignment, whereby all objects are assigned the same value, as in this example:

a = b = c = 11

Python Assignment Operators

OperatorUse
=Assignment
+=Increment assignment
-=Decrement assignment
*=Multiplication assignment
/=Division assignment
%=Modulus assignment
**=Exponential assignment
<<=Left shift assignment
>>=Right shift assignment
&=And assignment
^=Xor assignment
|=Or assignment

Python supports a pretty standard set of comparison operators. They behave much as expected, except in the case of the < or >, which may be used in combination. The following sequence

>>> 3 > 2 > 1

is invalid in many languages, and actually means (3 > 2) and (2 > 1).

Python Comparison Operators

OperatorUse
==Numeric is equal to
!=Numeric is not equal to
<>Alternate numeric is not equal to
>Numeric is greater than
<Numeric is less than
>=Numeric ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.