Operators

Precap

Operators are used for assignments and expressions. They can be divided into the following groups.

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 is int

  • If the data type of one of the two numbers is float, then the data type of the result is float

And since Python 3:

  • If the operator is / (division), then the data type of the result is always float

Operator

Name

Examples

Result


Python 2

Python 3

+

Addition

1 + 2
1 + 2.0

3
3.0

3
3.0

-

Subtraction

2 - 3
2 - 3.0

-1
-1.0

-1
-1.0

*

Multiplication

3 * 4
3 * 4.0

12
12.0

12
12.0

/

Division

4 / 2
5 / 3
5 / 3.0

2
1
1.6666666666666667

2.0
1.6666666666666667
1.6666666666666667

//

Floor division

5 // 3
5 // 3.0

1
1.0

1
1.0

%

Modulo (= remainder)

5 % 3
5 % 3.0

2
2.0

2
2.0

**

Exponentiation

2 ** 3
2 ** 3.0

8
8.0

8
8.0

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
1 < 2

False
True

<=

Less than or equal to

1 <= 1
1 <= 2

True
True

==

Equal to

1 == 1
1 == 2

True
False

>=

Greater than or equal to

1 >= 1
1 >= 2

True
False

>

Greater than

1 > 1
1 > 2

False
False

!=

Not equal to

1 != 1
1 != 2

False
True

Comparison operators with numeric data types 'int' and 'float'

Comparison operators with sequence data types 'str', 'tuple' and 'list'