Download - All IT eBooks

Transcript
CHAPTER 3 ■ VARIABLES AND DATA TYPES
>>> float(23)
23.0
>>> int(23.5)
23
>>> float(int(23.5))
23
There are a few gotchas when it comes to converting types; notice that float(int(x)) in the
preceding example loses its fractional part. Not all conversions are reversible, and the result of the
conversion may not be equal to the input value any more.
Working with Base 8 (Octal) and Base 16 (Hexadecimal)
It is possible to input and display integers in other formats such as base 16 (hexadecimal) or base 8 (octal).
Integers can be entered in octal form by putting a 0o in front of the octal number (that’s the number zero
followed by the letter o) and in hexadecimal by putting 0x (zero followed by x) in front of the hexadecimal
number. In hexadecimal, you use the letters A to F to represent the decimal numbers 10 to 15.
>>> octal number = 0o12
>>> hexadecimal number = 0xFC6
>>> print(octal number)
10
>>> print(hexadecimal number)
4038
Let’s break things down to see what’s going on here. In a decimal number, the positions of the digits
represent: units, tens, hundreds, thousands and so on—in reverse order. In hexadecimal and octal
numbers, the positions represent exponents of the numerical base. In octal, these positions would
represent units, 8s and 64s, for example, because 8 is the numerical base of octal.
You can work out the decimal value by multiplying the digits according to the value of their position
and adding the results together, as shown in Tables 3-2, 3-3, and 3-4. The first row in these tables is the
value of the position in the number, the second the multiplication sign to show that the value of the
position is multiplied by the digit in that position, the third the number in question, and the fourth the
results of the multiplication. Table 3-2 shows a decimal to give you the idea.
Table 3-2. Decimal 2037
1000
100
*
*
2
0
2000
+
0
+
10
1
3
7
30
+
7
=
2037 (decimal)
41