Operators
Mathematical operators like +
, -
, *
, /
and %
work as expected in Python.
A note that division (/
) behaves as mathematically expected (returning a float
).
If you want the integer division behaviour of C++, use floor division //
!
>>> 5/3
1.6666666666666667
>>> 5//3
1
Python also has a power/exponentiation operator **
. So the code below computes \(2^3\).
>>> 2**3
8
Comparison operators
Comparison operators <
, >
, <=
, >=
, ==
, !=
are the same as in C++. You can additionally chain expressions together.
>>> x = 5
>>> 3 < x < 6
True
>>> 5 < x <= 8
False
Logical Operators
Logical operators !
, &&
, ||
in C++ are in plain English in Python (not
, and
, or
).
>>> not True
>>> True and False
>>> True or False
>>> x = 7
>>> y = 2
>>> x > 3 and y < 1
>>> not x >= 5 and x < 3 # make sure you understand the
>>> not (x >= 5 and x < 3) # difference between these two
>>> not 5 + y > 3 * x or 4 == x + 3