官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 德清县| 漳州市| 浦北县| 泰安市| 青神县| 天等县| 宁陵县| 钟祥市| 古交市| 安图县| 花莲县| 介休市| 达日县| 临朐县| 湘乡市| 孝义市| 陆川县| 徐水县| 延庆县| 周口市| 绥中县| 阿荣旗| 蓬莱市| 于田县| 临澧县| 庐江县| 宁津县| 淳安县| 张家界市| 吉安县| 台湾省| 文昌市| 韶关市| 宜都市| 卓尼县| 长白| 博客| 时尚| 兴文县| 枝江市| 洪洞县|