- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
2.4 Operators
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. Python has two division operators, a single slash character for classic division and a double-slash for “floor” division (rounds down to nearest whole number). Classic division means that if the operands are both integers, it will perform floor division, while for floating point numbers, it represents true division. If true division is enabled, then the division operator will always perform that operation, regardless of operand types. You can read more about classic, true, and floor division in Chapter 5, “Numbers.”
There is also 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. Let us look at an example:
>>> print -2 * 4 + 3 ** 2 1
As you can see, the operator precedence is what you expect: + and - are at the bottom, followed by *, /, //, and %; then comes the unary + and -, and finally, we have ** at the top. ((3 ** 2) is calculated first, followed by (-2 * 4),then both results are summed together.)
Python also provides the standard comparison operators, which return a Boolean value indicating the truthfulness of the expression:
< <= > >= == != <>
Trying out some of the comparison operators we get:
>>> 2 < 4 True >>> 2 == 4 False >>> 2 > 4 False >>> 6.2 <= 6 False >>> 6.2 <= 6.2 True >>> 6.2 <= 6.20001 True
Python currently supports two “not equal” comparison operators, != and <>. These are the C-style and ABC/Pascal-style notations. The latter is slowly being phased out, so we recommend against its use.
Python also provides the expression conjunction operators:
and or not
We can use these operations to chain together arbitrary expressions and logically combine the Boolean results:
>>> 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 may be invalid in other languages, but in Python it is really a short way of saying:
>>> 3 < 4 and 4 < 5
You can find out more about Python operators in Section 4.5 of the text.