Expressions, operators, and data types
Python expressions are built from operators and operands. In Chapter 2, Simple Data Types, we introduced some of the basics of number and string operands, and looked at the variety of operators. We'll summarize the details here so that we can address some additional operator features.
Our numeric operands form a "tower", with types including:
The Fraction
and Decimal
class definitions must be imported, the other three classes are built-in. We typically use a statement such as from fractions import Fraction
.
The idea behind the tower is that many arithmetic operators coerce operands up the tower from integer to float to complex. Most of the time, this fits with our implicit mathematical expectations. We would be unhappy if we had to write explicit conversions to compute 2.333*3
. Python's arithmetic rules assure us that we'll get the expected floating-point result.
The Decimal
class doesn't fit well with the implicit coercion rules: in the rare case of trying to do arithmetic between float
and Decimal
, it's unclear how to go about it. An attempt to make a Decimal
value from a float
value will expose tiny errors because float
values are an approximation. An attempt to make a float
value from a Decimal
value subverts the Decimal
objective of yielding exact results. In the face of this ambiguity, an exception will be raised. This means that we'll need to write explicit conversions.
String objects are not implicitly coerced into numeric values. We must explicitly convert a string to a number. The int()
, float()
, complex()
, Fraction()
, and Decimal()
functions convert a string to a number object of the appropriate class.
We can group operators into a number of categories.
- Arithmetic:
+
,-
,*
,**
,/
,//
,%
- Bit-oriented:
<<
,>>
,&
,|
,^
,~
- Comparison:
<
,>
,<=
,>=
,==
,!=
The bit-oriented operators are supported by operands of the int
class. The other number classes don't have useful implementations of these operators. The bit-oriented operators are also defined for sets, something we'll look at in Chapter 6, More Complex Data Types.
Using operators on non-numeric data
We can apply some of the arithmetic operators to strings, bytes, and tuples. The results are focused on creating larger strings or larger tuples from smaller pieces. Here are some examples of this:
>>> "Hello " + "world" 'Hello world' >>> "<+>"*4 '<+><+><+><+>' >>> "<+>"*-2 ''
In the first example, we applied +
to two strings. In the second example, we applied *
between a str
and an int
. Interestingly, Python produces a string result by concatenating several copies of the original string object. Multiplying by any negative number creates a zero-length string.