Operators in Python
The standard mathematical operators that you are familiar with work the same way in Python as in most other languages.
+ – * / % **
Addition, subtraction, multiplication, division, and modulus/remainder are all part of the standard set of operators. In addition, Python provides an exponentiation operator, the double star/asterisk ( ** ). Although we are emphasizing the mathematical nature of these operators, please note that some of these operators are overloaded for use with other data types as well, for example, strings and lists.
>>> 3**2 9 >>> -2*4+3**2 1 >>> print -2*4+3**2 1
Although the example in the print statement is a valid mathematical statement, with Python’s hierarchical rules dictating the order in which operations are applied, adhering to good programming style means properly placing parentheses to indicate visually the grouping you have intended (see exercises). Anyone maintaining your code will thank you, and you will thank you.
Python also provides the standard comparison operators:
< <= > >= == != <>
Trying out some of the comparison operators we get:
>>> 2<4 True >>> 2 ==4 False >>> 2 >4 False >>> 6.2 >= 6 True >>> 6.2<=6 False >>> 6.2<=6.20001 True
Python also provides the expression conjunction operators:
and or not
Using these operators along with grouping parentheses, we can “chain” some of our comparisons together:
>>> (2<4) and (2==4) False >>> (2>4) or (2<4) True >>> not(6.2<=6) True >>> 3<4<5 True
The last example is an expression that maybe invalid in other languages, but in Python it is really a short way of saying:
>>> (3<4) and (4<5) True