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. 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.

>>> print -2 * 4 + 3 ** 2
1

As you can see from above, all operator priorities are what you expect: + and - at the bottom, followed by *, /, and %, then comes the unary + and -, and finally, ** at the top. (3 ** 2 is calculated first, followed by -2 * 4, then both results are summed together.)

CORE STYLE: Use parentheses

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
1
>>> 2 == 4
0
>>> 2 > 4
0
>>> 6.2 <= 6
0
>>> 6.2 <= 6.2
1
>>> 6.2 <= 6.20001
1

Python currently supports two “not equals” 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
					

Using these operators along with grouping parentheses, we can “chain” some of our comparisons together:

>>> (2 < 4) and (2 == 4)
0
>>> (2 > 4) or (2 < 4)
1
>>> not (6.2 <= 6)
1
>>> 3 < 4 < 5

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)

You can find out more about Python operators in Section 4.5of the text.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset