Text stringlengths 1 9.41k |
|---|
Floating-point numbers have a
decimal point and/or an optional signed exponent introduced by an `e or E and`
followed by an optional sign. |
If you write a number with a decimal point or exponent, Python makes it a floating-point object and uses floating-point (not integer)
math when the object is used in an expression. |
Floating-point numbers are implemented as C “doubles,” and therefore get as much precision as the C compiler used
to build the Python interpreter gives to doubles.
**|**
-----
_Integers in Python 2.6: normal and long_
In Python 2.6 there are two integer types, normal (32 bits) and long (unlimited
precision), and an... |
Because of this, integers can no longer be coded with a
trailing l or L, and integers never print with this character either. |
Apart from this,
most programs are unaffected by this change, unless they do type testing that
checks for 2.6 long integers.
_Hexadecimal, octal, and binary literals_
Integers may be coded in decimal (base 10), hexadecimal (base 16), octal (base 8),
or binary (base 2). |
Hexadecimals start with a leading 0x or 0X, followed by a string
of hexadecimal digits (0–9 and A–F). Hex digits may be coded in lower- or uppercase. |
Octal literals start with a leading 0o or 0O (zero and lower- or uppercase letter
“o”), followed by a string of digits (0–7). |
In 2.6 and earlier, octal literals can also
be coded with just a leading 0, but not in 3.0 (this original octal form is too easily
confused with decimal, and is replaced by the new 0o format). |
Binary literals, new
in 2.6 and 3.0, begin with a leading 0b or 0B, followed by binary digits (0–1).
Note that all of these literals produce integer objects in program code; they are just
alternative syntaxes for specifying values. |
The built-in calls `hex(I),` `oct(I), and`
```
bin(I) convert an integer to its representation string in these three bases, and
int(str, base) converts a runtime string to an integer per a given base.
```
_Complex numbers_
Python complex literals are written as `realpart+imaginarypart, where the`
```
imaginarypa... |
The realpart is technically optional, so
```
the imaginarypart may appear on its own. |
Internally, complex numbers are implemented as pairs of floating-point numbers, but all numeric operations perform
complex math when applied to complex numbers. |
Complex numbers may also be
created with the complex(real, `imag) built-in call.`
_Coding other numeric types_
As we’ll see later in this chapter, there are additional, more advanced number types
not included in Table 5-1. |
Some of these are created by calling functions in imported modules (e.g., decimals and fractions), and others have literal syntax all
their own (e.g., sets).
**|**
-----
###### Built-in Numeric Tools
Besides the built-in number literals shown in Table 5-1, Python provides a set of tools
for processing number objec... |
Floating-point numbers, for example, have an as_integer_ratio method that
is useful for the fraction number type, and an is_integer method to test if the number
is an integer. |
Integers have various attributes, including a new bit_length method in
the upcoming Python 3.1 release that gives the number of bits necessary to represent
the object’s value. |
Moreover, as part collection and part number, sets also support both
methods and expressions.
Since expressions are the most essential tool for most number types, though, let’s turn
to them next.
###### Python Expression Operators
Perhaps the most fundamental tool that processes numbers is the expression: a combinat... |
In Python, expressions are written using the usual mathematical
notation and operator symbols. |
For instance, to add two numbers X and Y you would
say X + Y, which tells Python to apply the + operator to the values named by X and Y.
The result of the expression is the sum of X and Y, another number object.
Table 5-2 lists all the operator expressions available in Python. |
Many are
self-explanatory; for instance, the usual mathematical operators (+, −, *, /, and so on)
are supported. |
A few will be familiar if you’ve used other languages in the past: % computes a division remainder, << performs a bitwise left-shift, & computes a bitwise AND
result, and so on. |
Others are more Python-specific, and not all are numeric in nature:
for example, the is operator tests object identity (i.e., address in memory, a strict form
of equality), and lambda creates unnamed functions.
**|**
-----
_Table 5-2. |
Python expression operators and precedence_
|Operators yield x|Description Generator function send protocol|
|---|---|
|lambda args: expression|Anonymous function generation|
|x if y else z|Ternary selection (x is evaluated only if y is true)|
|x or y|Logical OR (y is evaluated only if x is false)|
|x and y|Logical AN... |
In Python
3.0, the latter of these options is removed because it is redundant. |
In either version,
best practice is to use X != Y for all value inequality tests.
- In Python 2.6, a backquotes expression `X` works the same as repr(X) and converts
objects to display strings. |
Due to its obscurity, this expression is removed in Python
3.0; use the more readable str and repr built-in functions, described in “Numeric
Display Formats” on page 115.
- The X // Y floor division expression always truncates fractional remainders in both
Python 2.6 and 3.0. |
The X / Y expression performs true division in 3.0 (retaining
remainders) and classic division in 2.6 (truncating for integers). |
See “Division:
Classic, Floor, and True” on page 117.
- The syntax [...] is used for both list literals and list comprehension expressions.
The latter of these performs an implied loop and collects expression results in a
new list. |
See Chapters 4, 14, and 20 for examples.
- The syntax `(...) is used for tuples and expressions, as well as generator`
expressions—a form of list comprehension that produces results on demand, instead of building a result list. |
See Chapters 4 and 20 for examples. |
The parentheses
may sometimes be omitted in all three constructs.
- The syntax {...} is used for dictionary literals, and in Python 3.0 for set literals
and both dictionary and set comprehensions. |
See the set coverage in this chapter
and Chapters 4, 8, 14, and 20 for examples.
- The yield and ternary if/else selection expressions are available in Python 2.5 and
later. |
The former returns send(...) arguments in generators; the latter is shorthand
for a multiline if statement. |
yield requires parentheses if not alone on the right
side of an assignment statement.
- Comparison operators may be chained: `X < Y < Z produces the same result as`
```
X < Y and Y < X. |
See “Comparisons: Normal and Chained” on page 116 for details.
```
- In recent Pythons, the slice expression X[I:J:K] is equivalent to indexing with a
slice object: X[slice(I, J, K)].
- In Python 2.X, magnitude comparisons of mixed types—converting numbers to a
common type, and ordering other mixed types according ... |
In Python 3.0, nonnumeric mixed-type magnitude comparisons are not
allowed and raise exceptions; this includes sorts by proxy.
- Magnitude comparisons for dictionaries are also no longer supported in Python
3.0 (though equality tests are); comparing sorted(dict.items()) is one possible
replacement.
We’ll see most of... |
For instance, the sum of two multiplications might be written as a mix of variables and operators:
```
A * B + C * D
```
So, how does Python know which operation to perform first? |
The answer to this question lies in operator precedence. |
When you write an expression with more than one
operator, Python groups its parts according to what are called precedence rules, and
this grouping determines the order in which the expression’s parts are computed.
Table 5-2 is ordered by operator precedence:
- Operators lower in the table have higher precedence, and ... |
Similarly, in this section’s original example, both multiplications (A * B
and C * D) will happen before their results are added.
###### Parentheses group subexpressions
You can forget about precedence completely if you’re careful to group parts of expressions with parentheses. |
When you enclose subexpressions in parentheses, you override
Python’s precedence rules; Python always evaluates expressions in parentheses first
before using their results in the enclosing expressions.
For instance, instead of coding X + Y * Z, you could write one of the following to force
Python to evaluate the expre... |
In the second case, the * is performed first (just as if there were no parentheses at all). |
Generally speaking, adding parentheses in large expressions is a good
idea—it not only forces the evaluation order you want, but also aids readability.
###### Mixed types are converted up
Besides mixing operators in expressions, you can also mix numeric types. |
For instance,
you can add an integer to a floating-point number:
```
40 + 3.14
```
**|**
-----
But this leads to another question: what type is the result—integer or floating-point?
The answer is simple, especially if you’ve used almost any other language before: in
mixed-type numeric expressions, Python first co... |
This
behavior is similar to type conversions in the C language.
Python ranks the complexity of numeric types like so: integers are simpler than floatingpoint numbers, which are simpler than complex numbers. |
So, when an integer is mixed
with a floating point, as in the preceding example, the integer is converted up to a
floating-point value first, and floating-point math yields the floating-point result. |
Similarly, any mixed-type expression where one operand is a complex number results in
the other operand being converted up to a complex number, and the expression yields
a complex result. |
(In Python 2.6, normal integers are also converted to long integers
whenever their values are too large to fit in a normal integer; in 3.0, integers subsume
longs entirely.)
You can force the issue by calling built-in functions to convert types manually:
`>>> int(3.1415)` _# Truncates float to integer_
```
3
```
`... |
In general, Python does not convert across
any other type boundaries automatically. |
Adding a string to an integer, for example,
results in an error, unless you manually convert one or the other; watch for an example
when we meet strings in Chapter 7.
In Python 2.6, nonnumeric mixed types can be compared, but no conversions are performed (mixed types compare according to a fixed but
arbitrary rule). |
In 3.0, nonnumeric mixed-type comparisons are not allowed and raise exceptions.
###### Preview: Operator overloading and polymorphism
Although we’re focusing on built-in numbers right now, all Python operators may be
overloaded (i.e., implemented) by Python classes and C extension types to work on
objects you create. |
For instance, you’ll see later that objects coded with classes may be
added or concatenated with + expressions, indexed with [i] expressions, and so on.
Furthermore, Python itself automatically overloads some operators, such that they
perform different actions depending on the type of built-in objects being processed.... |
In fact, + can
mean anything at all when applied to objects you define with classes.
As we saw in the prior chapter, this property is usually called polymorphism—a term
indicating that the meaning of an operation depends on the type of the objects being
operated on. |
We’ll revisit this concept when we explore functions in Chapter 16, because it becomes a much more obvious feature in that context.
###### Numbers in Action
On to the code! |
Probably the best way to understand numeric objects and expressions
is to see them in action, so let’s start up the interactive command line and try some
basic but illustrative operations (see Chapter 3 for pointers if you need help starting an
interactive session).
###### Variables and Basic Expressions
First of all... |
In the following interaction, we first assign
two _variables (a and_ `b) to integers so we can use them later in a larger expression.`
Variables are simply names—created by you or Python—that are used to keep track of
information in your program. |
We’ll say more about this in the next chapter, but in
Python:
- Variables are created when they are first assigned values.
- Variables are replaced with their values when used in expressions.
- Variables must be assigned before they can be used in expressions.
- Variables refer to objects and are never declared... |
Recall that in Python code, text after a_ `# mark and`
continuing to the end of the line is considered to be a comment and is ignored. |
Comments are a way to write human-readable documentation for your code. |
Because code
you type interactively is temporary, you won’t normally write comments in this context,
but I’ve added them to some of this book’s examples to help explain the code.[*] In the
next part of the book, we’ll meet a related feature—documentation strings—that attaches the text of your comments to objects.
- If... |
At this point, the values of
```
a and b are still 3 and 4, respectively. |
Variables like these are replaced with their values
```
whenever they’re used inside an expression, and the expression results are echoed back
immediately when working interactively:
`>>> a + 1, a – 1` _# Addition (3 + 1), subtraction (3 - 1)_
```
(4, 2)
```
`>>> b * 3, b / 2` _# Multiplication (4 * 3), division (... |
Note that the expressions
work because the variables a and b within them have been assigned values. |
If you use
a different variable that has never been assigned, Python reports an error rather than
filling in some default value:
```
>>> c * 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'c' is not defined
```
You don’t need to predeclare variables in Python, but they must ... |
In practice, this means you have to initialize counters to zero before you can add to them, initialize lists to an empty list before you can
append to them, and so on.
Here are two slightly larger expressions to illustrate operator grouping and more about
conversions:
`>>> b / 2 + a` _# Same as ((4 / 2) + 3)_
```
5... |
The result is as if the expression had
```
been organized with parentheses as shown in the comment to the right of the code.
Also, notice that all the numbers are integers in the first expression. |
Because of that,
Python 2.6 performs integer division and addition and will give a result of 5, whereas
Python 3.0 performs true division with remainders and gives the result shown. |
If you
want integer division in 3.0, code this as b // 2 + a (more on division in a moment).
In the second expression, parentheses are added around the + part to force Python to
evaluate it first (i.e., before the /). |
We also made one of the operands floating-point by
adding a decimal point: 2.0. |
Because of the mixed types, Python converts the integer
**|**
-----
referenced by a to a floating-point value (3.0) before performing the +. |
If all the numbers
in this expression were integers, integer division (4 / 5) would yield the truncated
integer 0 in Python 2.6 but the floating-point 0.8 in Python 3.0 (again, stay tuned for
division details).
###### Numeric Display Formats
Notice that we used a print operation in the last of the preceding examples. |
Without
the print, you’ll see something that may look a bit odd at first glance:
`>>> b / (2.0 + a)` _# Auto echo output: more digits_
```
0.80000000000000004
```
`>>> print(b / (2.0 + a))` _# print rounds off digits_
```
0.8
```
The full story behind this odd result has to do with the limitations of floating-po... |
In fact,
this is really just a display issue—the interactive prompt’s automatic result echo shows
more digits than the print statement. |
If you don’t want to see all the digits, use print;
as the sidebar “str and repr Display Formats” on page 116 will explain, you’ll get a
user-friendly display.
Note, however, that not all values have so many digits to display:
```
>>> 1 / 2.0
0.5
```
and that there are more ways to display the bits of a number in... |
Normal comparisons work for numbers
exactly as you’d expect—they compare the relative magnitudes of their operands and
return a Boolean result (which we would normally test in a larger statement):
`>>> 1 < 2` _# Less than_
```
True
```
`>>> 2.0 >= 1` _# Greater than or equal: mixed-type 1 converted to 1.0_
```
Tr... |
Chained comparisons are a sort of shorthand for larger Boolean expressions. In short, Python lets us string together magnitude comparison tests to code
chained comparisons such as range tests. |
The expression (A < B < C), for instance,
tests whether B is between A and C; it is equivalent to the Boolean test (A < B and B <
```
C) but is easier on the eyes (and the keyboard). |
For example, assume the following
```
assignments:
**|**
-----
```
>>> X = 2
>>> Y = 4
>>> Z = 6
```
The following two expressions have identical effects, but the first is shorter to type, and
it may run slightly faster since Python needs to evaluate Y only once:
`>>> X < Y < Z` _# Chained comparisons: ran... |
The following, for
instance, is false just because 1 is not equal to 2:
`>>> 1 == 2 < 3` _# Same as: 1 == 2 and 2 < 3_
```
False # Not same as: False < 3 (which means 0 < 3, which is true)
```
Python does not compare the 1 == 2 False result to 3—this would technically mean
the same as 0 < 3, which would be ... |
In fact, there are actually three flavors
of division, and two different division operators, one of which changes in 3.0:
```
X / Y
```
_Classic and true division. |
In Python 2.6 and earlier, this operator performs classic_
division, truncating results for integers and keeping remainders for floating-point
numbers. |
In Python 3.0, it performs true division, always keeping remainders regardless of types.
```
X // Y
```
_Floor division. |
Added in Python 2.2 and available in both Python 2.6 and 3.0, this_
operator always truncates fractional remainders down to their floor, regardless of
types.
**|**
-----
True division was added to address the fact that the results of the original classic division
model are dependent on operand types, and so can be ... |
Classic division was removed in 3.0 because of
this constraint—the / and // operators implement true and floor division in 3.0.
In sum:
- In 3.0, the / now always performs true division, returning a float result that includes
any remainder, regardless of operand types. |
The // performs floor division, which
truncates the remainder and returns an integer for integer operands or a float if any
operand is a float.
- In 2.6, the / does classic division, performing truncating integer division if both
operands are integers and float division (keeping remainders) otherwise. |
The //
does floor division and works as it does in 3.0, performing truncating division for
integers and floor division for floats.
Here are the two operators at work in 3.0 and 2.6:
```
C:\misc> C:\Python30\python
>>>
```
`>>> 10 / 4` _# Differs in 3.0: keeps remainder_
```
2.5
```
`>>> 10 // 4` _# Same in 3.0... |
Although this may
seem similar to the type-dependent behavior of / in 2.X that motivated its change in
3.0, the type of the return value is much less critical than differences in the return value
itself. |
Moreover, because // was provided in part as a backward-compatibility tool for
programs that rely on truncating integer division (and this is more common than you
might expect), it must return integers for integers.
**|**
-----
###### Supporting either Python
Although / behavior differs in 2.6 and 3.0, you can sti... |
If your programs depend on truncating integer division, use // in both 2.6 and
3.0. |
If your programs require floating-point results with remainders for integers, use
```
float to guarantee that one operand is a float around a / when run in 2.6:
X = Y // Z # Always truncates, always an int result for ints in 2.6 and 3.0
X = Y / float(Z) # Guarantees float division with remainder in either 2.6 or... |
The net effect is to round down,
not strictly truncate, and this matters for negatives. |
You can see the difference for
yourself with the Python math module (modules must be imported before you can use
their contents; more on this later):
```
>>> import math
>>> math.floor(2.5)
2
>>> math.floor(-2.5)
-3
>>> math.trunc(2.5)
2
>>> math.trunc(-2.5)
-2
```
When running division operators, yo... |
Here’s the case for 3.0:
```
C:\misc> c:\python30\python
>>> 5 / 2, 5 / −2
(2.5, −2.5)
```
`>>> 5 // 2, 5 // −2` _# Truncates to floor: rounds to first lower integer_
```
(2, −3) # 2.5 becomes 2, −2.5 becomes −3
>>> 5 / 2.0, 5 / −2.0
(2.5, −2.5)
```
**|**
-----
`>>> 5 // 2.0, 5 // −2.0` _# D... |
Perhaps because of a C language
legacy, many programmers rely on division truncation for integers and will have to
learn to use // in such contexts instead. |
Watch for a simple prime number while loop
example in Chapter 13, and a corresponding exercise at the end of Part IV that illustrates
the sort of code that may be impacted by this / change. |
Also stay tuned for more on
the special from command used in this section; it’s discussed further in Chapter 24.
###### Integer Precision
Division may differ slightly across Python releases, but it’s still fairly standard. |
Here’s
something a bit more exotic. |
As mentioned earlier, Python 3.0 integers support unlimited size:
```
>>> 999999999999999999999999999999 + 1
1000000000000000000000000000000
```
Python 2.6 has a separate type for long integers, but it automatically converts any
number too large to store in a normal integer to this type. |
Hence, you don’t need to
code any special syntax to use longs, and the only way you can tell that you’re using
2.6 longs is that they print with a trailing “L”:
```
>>> 999999999999999999999999999999 + 1
1000000000000000000000000000000L
```
Unlimited-precision integers are a convenient built-in tool. |
For instance, you can use
them to count the U.S. national debt in pennies in Python directly (if you are so inclined,
and have enough memory on your computer for this year’s budget!). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.