• Tidak ada hasil yang ditemukan

Chapter 3 Chapter 3

13.11 Numeric Data Types

# change.py

# A program to calculate the value of some change in dollars def main () :

print ("Change Counter") print ()

print ("Please enter the count of each coin type. ") quarters = eval (input ("Quarters: ") )

dimes = eval (input ("Dimes: ") )

nickels = eval (input ("Nickels: ") ) pennies = eval (input ("Pennies: ") )

total = quarters

*

.25 + dimes

*

.10 + nickels

*

.05 + pennies

*

.01

print ()

print ("The total value of your change is", total) main ()

Here is an example of the output:

Change Counter

Please enter the count of each coin type.

Quarters: 5

Dimes: 3 Nickels: 4 Pennies: 6

The total value of your change is 1.81

This program actually manipulates two different kinds of numbers. The val­

ues entered by the user (5, 3, 4, 6) are whole numbers; they don't have any fractional part. The values of the coins (.25, .10, .OS, .01) are decimal repre­

sentations of fractions. Inside the computer, whole numbers and numbers that have fractional components are stored differently. Technically, we say that these are two different data types.

The data type of an object determines what values it can have and what operations can be performed on it. Whole numbers are represented using the integer data type (int for short). Values of type int can be positive or nega­

tive whole numbers. Numbers that can have fractional parts are represented as

floating-point (or float) values. So how do we tell whether a number is an int or

3.1. Numeric Data Types

a float? A numeric literal that does not contain a decimal point produces an int value, but a literal that has a decimal point is represented by a float (even if the fractional part is 0).

Python provides a special function called

type

that tells us the data type (or

"class") of any value. Here is an interaction with the Python interpreter showing the difference between int and float literals:

>>> type (3)

<class 'int' >

>>> type (3. 14)

<class 'float' >

>>> type (3. 0)

<class 'float' >

>>> mylnt = -32

>>> type (mylnt)

<class 'int' >

>>> myFloat = 32. 0

>>> type (myFloat)

<class 'float' >

You may be wondering why there are two different data types for numbers.

One reason has to do with program style. Values that represent counts can't be fractional; we can't have 3 � quarters, for example. Using an int value tells the reader of a program that the value can't be a fraction. Another reason has to do with the efficiency of various operations. The underlying algorithms that per­

form computer arithmetic are simpler, and can therefore be faster, for ints than the more general algorithms required for float values. Of course, the hardware implementations of floating-point operations on modem processors are highly optimized and may be just as fast the int operations.

Another difference between ints and floats is that the float type can only represent approximations to real numbers.

As

we will see, there is a limit to the precision, or accuracy, of the stored values. Since float values are not exact, while ints always are, your general rule of thumb should be: If you don't need fractional values, use an int.

A value's data type determines what operations can be used on it. As we have seen, Python supports the usual mathematical operations on numbers. Table 3.1 summarizes these operations. Actually, this table is somewhat misleading. Since these two types have differing underlying representations, they each have their own set of operations. For example, I have listed a single addition operation, but

59

operator operation

+

addition

-

subtraction

*

multiplication I float division

**

exponentiation

abs ()

absolute value II integer division

%

remainder

Table 3.1: Python built-in numeric operations

keep in mind that when addition is performed on floats, the computer hardware performs a floating-point addition, whereas with ints the computer performs an integer addition. Python chooses the appropriate underlying operation (int or float) based on the operands.

Consider the following interaction with Python:

>>> 3 + 4 7

>>> 3. 0 + 4. 0 7. 0

>>> 3

*

4 12

>>> 3. 0

*

4. 0 12. 0

>>> 4

**

3 64

>>> 4. 0

**

3 64. 0

>>> 4. 0

**

3.0 64. 0

>>> abs (5) 5

>>> abs (-3.5) 3.5

>>>

For the most part, operations on floats produce floats, and operations on ints

3.1. Numeric Data Types

produce ints. Most of the time, we don't even worry about what type of oper­

ation is being performed; for example, integer addition produces pretty much the same result as floating-point addition, and we can rely on Python to do the right thing.

In the case of division, however, things get a bit more interesting.

As

the table shows, Python (as of version 3.0) provides two different operators for division. The usual symbol

(I)

is used for "regular" division and a double slash

(I I)

is used to indicate integer division. The best way to get a handle on the difference between these two is to try them out.

>>> 10 I 3

3.3333333333333335

>>> 10.0 I 3.0

3.3333333333333335

>>> 10 I 5 2.0

>>> 10 II 3 3

>>> 10.0 II 3.0 3.0

>>> 10

%

3 1

>>> 10.0

%

3.0 1.0

Notice that the

I

operator always returns a float. Regular division often pro­

duces a fractional result, even though the operands may be ints. Python accom­

modates this by always returning a floating-point number. Are you surprised that the result of

1013

has a 5 at the very end? Remember, floating-point val­

ues are always approximations. This value is as close as Python can get when representing 3 � as a floating-point number.

To get a division that returns an integer result, you can use the integer divi­

sion operation

I I.

Integer division always produces an integer. Think of integer division as "gozinta." The expression

10 I I 3

produces 3 because three gozinta (goes into) ten three times (with a remainder of one). While the result of inte­

ger division is always an integer, the data type of the result depends on the data type of the operands. A float integer-divided by a float produces a float with a 0 fractional component. The last two interactions demonstrate the remainder operation %. The remainder of integer-dividing 10 by 3 is 1. Notice again that the data type of the result depends on the type of the operands.

61

Depending on your math background, you may not have used the integer division or remainder operations before. The thing to keep in mind is that these two operations are closely related. Integer division tells you how many times one number goes into another, and the remainder tells you how much is left over. Mathematically you could write the idea like this: a= (a/ /b)(b)

+

(a%b).

As an example application, suppose we calculated the value of our loose change in cents (rather than dollars). If I have 383 cents, then I can find the number of whole dollars by computing 383//100 = 3, and the remaining change is 383%100 = 83. Thus, I must have a total of three dollars and 83 cents in change.

By the way, although Python (as of version 3.0) treats regular division and integer division as two separate operators, many other computer languages (and earlier Python versions) just use

I

to signify both. When the operands are ints,

I

means integer division, and when they are floats, it signifies regular division.

This is a common source of errors. For example, in our temperature conversion program the formula

915 * celsius + 32

would not compute the proper re­

sult, since

915

would evaluate to

1

using integer division. In these languages,

you need to be careful to write this expression as

9. 015.0 * celsius + 32

so

that the proper form of division is used, yielding a fractional result.