2. Operators
An operator is, in general, a typographical symbol that means something special to the Python interpreter, and tells it to do something with the literals or variables next to it. Many are basic mathematical functions like addition and subtraction. Comparison functions are also operators.
A. Mathematical operators
Python supports unary operators for no change and negation, + and -, respectively; and binary arithmetic operators +, -, *, /, //, %, and **, for addition, subtraction, multiplication, division, floor division, modulo, and exponentiation, respectively.
+expr # expr sign unchanged
-expr # negation of expr
expr1 ** expr2 # expr1 raised to the power of expr2a
expr1 * expr2 # expr1 times expr2
expr1 / expr2 # expr1 divided by expr2 (classic division)
expr1 // expr2 # expr1 divided by expr2 (floor division)
expr1 % expr2 # expr1 modulo expr2
expr1 + expr2 # expr1 plus expr2
expr1 - expr2 # expr1 minus expr2
Python recognizes the following mathematical operators:
+ Addition; also used for string concatenation
five = 2+3
company = "Levis" + " Strauss " + "Co"
- Subtraction; will also yield the negative of a number
three = 5-2
minusfive = -5
* Multiplication; can also be used for repeating strings
fivesquared = 5*5
threecheers = "Rah! "*3 # produces "Rah! Rah! Rah! "
** Exponentiation; the double asterisk indicates that the first number is to be taken to the power of the second number
fivesquared = 5**2
/ Division; classical division
three = 6/2
There is a big caveat here. If you divide two integers, or an integer and a float, or two floats, the result will be a float. So you always get the full value of the quotient.
quotient = 7/2 # result: 3.5 (a float)
// Floor division; this gives the quotient sans remainder.
quotient = 7//2 # result is 3 in any version of Python
% Modulo operator; this gives the remainder of a division:
remainder = 7%2 # result is 1, since 7/2 = 3 remainder 1
B. Comparison operators
Comparison operators are used to determine equality of two data values between members of the same type. These comparison operators are supported for all built-in types. Comparisons yield Boolean True or False values, based on the validity of the comparison expression.
Note that comparisons performed are those that are appropriate for each data type. In other words, numeric types will be compared according to numeric value in sign and magnitude, strings will compare lexicographically, etc.
expr1 < expr2 # is expr1 is less than expr2 ?
expr1 > expr2 # is expr1 is greater than expr2 ?
expr1 <= expr2 # is expr1 is less than or equal to expr2 ?
expr1 >= expr2 # is expr1 is greater than or equal to expr2 ?
expr1 == expr2 # is expr1 is equal to expr2 ?
expr1 != expr2 # is expr1 is not equal to expr2 (C-style) ?
Python recognizes the following comparison operators:
< Less than, > Greater than
2 < 5 # yields 'True'
2 <= 2 # yields 'True'
== Equal to, != Not equal to
3==5 # yields 'False'
"Cat" != "Dog" # yields 'True'
"abc" == "xyz" # yields 'False'
"abc" > "xyz" # yields 'False'
"abc" < "xyz" # yields 'True'
C. Boolean operators
Expressions may be linked together or negated using the Boolean logical operators and, or, and not, all of which are Python keywords. The not operator has the highest precedence and is immediately one level below all the comparison operators. The and and or operators follow, respectively.
not expr # Logical NOT of expr (negation)
expr1 and expr2 # Logical AND of expr1 and expr2 (conjunction)
expr1 or expr2 # Logical OR of expr1 and expr2 (disjunction)
These operators, in contrast to the symbols seen thus far, are simple words, which perform Boolean logic on 'True' and 'False' data.
and - Boolean AND
a and b # Returns 'True' if both a and b are 'True' and 'False' otherwise
or - Boolean OR
a or b # Returns 'True' if either a or b are 'True' and 'False' otherwise
not - Boolean NOT
not a # Returns 'True' if a is 'False' and 'False' if a is 'True'
D. Operator precedence
There is an order of operations for operators, just like in standard algebra, and it generally follows the same rules. The top-priority operators are executed first, then the lower-priority ones. Here is the list of operators in descending order of priority:
- - Negation (i.e., a negative sign in front of one number takes priority over all else)
- ** Exponentiation
- *, /, // , % Multiplication, division, floor division, modulo (all same priority; evaluated in left-to-right order)
- +,- Addition, subtraction
- All comparison operators (<, >, <=, =>,==, !=)
- All Boolean operators (and, or, not)
So for a complex example:
-5 ** 2 < 2 or 2 + 5 * 2 == 12
This line of code will be evaluated as follows:
- Square the number -5 (get +25) and see if it's less than 2 (returns False)
- Multiply 5 by 2 and add 2 (get 10+2, or 12) and see if it's the same as 12 (returns True)
- Check if either the left hand side or right hand side were True (the right side was), and return True if so
So the example has the value 'True'.
Parentheses can be used to order operations just like in algebra, and are recommended if only for your own sanity!
( ((-5)**2) < 2 ) or ( (2+(5*2)) == 12 )
is, at the least, much easier to read.