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 + 4.0, 2.0 ** b # Mixed-type conversions(6.0, 16.0)Technically, the results being echoed back here are tuples of two values because thelines typed at the prompt contain two expressions separated by commas; that’s whythe results are displayed in parentheses (more on tuples later). Note that the expressionswork because the variables a and b within them have been assigned values. Ifyou use a different variable that has never been assigned, <strong>Python</strong> reports an errorrather than filling in some default value:>>> c * 2Traceback (most recent call last):File "", line 1, in ?NameError: name 'c' is not definedYou don’t need to predeclare variables in <strong>Python</strong>, but they must have been assignedat least once before you can use them at all. In practice, this means you have to initializecounters to zero before you can add to them, initialize lists to an empty listbefore you can append to them, and so on.Here are two slightly larger expressions to illustrate operator grouping and moreabout conversions:>>> b / 2 + a # Same as ((4 / 2) + 3)5>>> print b / (2.0 + a) # Same as (4 / (2.0 + 3))0.8In the first expression, there are no parentheses, so <strong>Python</strong> automatically groups thecomponents according to its precedence rules—because / is lower in Table 5-2 than+, it binds more tightly, and so is evaluated first. The result is as if the expression hadparentheses as shown in the comment to the right of the code. Also, notice that allthe numbers are integers in the first expression; because of that, <strong>Python</strong> performsinteger division and addition.In the second expression, parentheses are added around the + part to force <strong>Python</strong> toevaluate it first (i.e., before the /). We also made one of the operands floating-pointby adding a decimal point: 2.0. Because of the mixed types, <strong>Python</strong> converts the integerreferenced by a to a floating-point value (3.0) before performing the +. It alsoconverts b to a floating-point value (4.0), and performs floating-point division; (4.0 /5.0) yields a floating-point result of 0.8. If all the numbers in this expression wereintegers, it would instead invoke integer division (4 /5), and the result would be thetruncated integer 0 (in <strong>Python</strong> 2.5, at least—see the discussion of true divisionahead).Numeric Display FormatsNotice that we used a print statement in the last of the preceding examples. Withoutthe print, you’ll see something that may look a bit odd at first glance:100 | Chapter 5: Numbers

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

Saved successfully!

Ooh no, something went wrong!