Operators
Precap
Operators are used for assignments and expressions. They can be divided into the following groups.
Assignment:
=Compound assigment:
+=,-=,*=,/=,//=,%=,**=Arithmetic:
+,-,*,/,//,%,**Comparison:
<,<=,==,>=,>,!=Binary:
&,|,~,^,<<,>>Identity:
is,is notMembership:
in,not in
Assignment
A single = sign is used to assign a literal value or expression to its left to a variable to its right.
The assignment operator '='
Compound assignment
Compound assignments are short versions of frequent assignments with a simple expression. E.g. counter = counter + 1 can also be written as counter += 1. All arithmetic +, -, *, /, //, %, ** and (almost) all bitwise operators &, |, ^, <<, >> can be used (= all except ~).
Compound assignment operators
In some other programming languages (e.g. JavaScript or C) an even shorter version for incrementing (= adding 1) and decrementing (= subtracting 1) exists: ++ and --. They are called unary operations and are not supported in Python.
Unary operators for incrementing or decrementing DO NOT WORK in Python but throw an error
Arithmetic
Arithmetic operators are most commonly used within basic arithmetic expressions. It’s important to know that the data type of the result depends on the data type(s) of the numbers used. There are 3 simple rules to be kept in mind:
If the data type of both numbers is
int, then the data type of the result isintIf the data type of one of the two numbers is
float, then the data type of the result isfloat
And since Python 3:
If the operator is
/(division), then the data type of the result is alwaysfloat
Operator |
Name |
Examples |
Result |
|
|---|---|---|---|---|
Python 2 |
Python 3 |
|||
+ |
Addition |
1 + 2
|
3
|
3
|
- |
Subtraction |
2 - 3
|
-1
|
-1
|
* |
Multiplication |
3 * 4
|
12
|
12
|
/ |
Division |
4 / 2
|
2
|
2.0
|
// |
Floor division |
5 // 3
|
1
|
1
|
% |
Modulo (= remainder) |
5 % 3
|
2
|
2
|
** |
Exponentiation |
2 ** 3
|
8
|
8
|
Arithmetic operators with numeric data types 'int' and 'float' in Python 3
The two arithmetic operators + and * also work with sequence data types.
Arithmetic operators with sequence data types 'str', 'tuple', 'list'
Comparison
Operator |
Name |
Examples |
Result |
|---|---|---|---|
< |
Less than |
1 < 1
|
False
|
<= |
Less than or equal to |
1 <= 1
|
True
|
== |
Equal to |
1 == 1
|
True
|
>= |
Greater than or equal to |
1 >= 1
|
True
|
> |
Greater than |
1 > 1
|
False
|
!= |
Not equal to |
1 != 1
|
False
|
Comparison operators with numeric data types 'int' and 'float'
Comparison operators with sequence data types 'str', 'tuple' and 'list'