12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

(2.0 + a) # Auto echo output: more digits0.80000000000000004>>> print b / (2.0 + a) # Print rounds off digits0.8The full story behind this odd result has to do with the limitations of floating-pointhardware, and its inability to exactly represent some values. Because computer architectureis well beyond this book’s scope, though, we’ll finesse this by saying that allof the digits in the first output are really there, in your computer’s floating-pointhardware—it’s just that you’re not normally accustomed to seeing them. I’ve usedthis example to demonstrate the difference in output formatting—the interactiveprompt’s automatic result echo shows more digits than the print statement. If youdon’t want to see all the digits, include the print.Note, however, that not all values have so many digits to display:>>> 1 / 2.00.5and that there are more ways to display the bits of a number inside your computerthan prints and automatic echoes:>>> num = 1 / 3.0>>> num # Echoes0.33333333333333331>>> print num # Print rounds0.333333333333>>> "%e" % num # String formatting'3.333333e-001'>>> "%2.2f" % num # String formatting'0.33'The last two of these employ string formatting, an expression that allows for formatflexibility, which we will explore in the upcoming chapter on strings (Chapter 7).str and repr Display FormatsTechnically, the difference between default interactive echoes and prints correspondsto the difference between the built-in repr and str functions:>>> repr(num) # Used by echoes: as-code form'0.33333333333333331'>>> str(num) # Used by print: user-friendly form'0.333333333333'Both of these convert arbitrary objects to their string representations: repr (and thedefault interactive echo) produces results that look as though they were code; str (andthe print statement) converts to a typically more user-friendly format. This notion willresurface when we study strings, and you’ll find more on these built-ins in general laterin the book.Numbers in Action | 101

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!