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.

Mixed Operators Follow Operator PrecedenceAs in most languages, in <strong>Python</strong>, more complex expressions are coded by stringingtogether the operator expressions in Table 5-2. For instance, the sum of two multiplicationsmight be written as a mix of variables and operators:A * B + C * DSo, how does <strong>Python</strong> know which operation to perform first? The answer to thisquestion lies in operator precedence. When you write an expression with more thanone operator, <strong>Python</strong> groups its parts according to what are called precedence rules,and this grouping determines the order in which the expression’s parts are computed.In Table 5-2, operators lower in the table have higher precedence, and so bindmore tightly in mixed expressions.For example, if you write X+Y*Z, <strong>Python</strong> evaluates the multiplication first (Y * Z),then adds that result to X because * has higher precedence (is lower in the table) than+. Similarly, in this section’s original example, both multiplications (A *Band C*D)will happen before their results are added.Parentheses Group SubexpressionsYou can forget about precedence completely if you’re careful to group parts ofexpressions with parentheses. When you enclose subexpressions in parentheses, youoverride <strong>Python</strong>’s precedence rules; <strong>Python</strong> always evaluates expressions in parenthesesfirst 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<strong>Python</strong> to evaluate the expression in the desired order:(X + Y) * ZX + (Y * Z)In the first case, + is applied to X and Y first, because this subexpression is wrapped inparentheses. In the second case, the * is performed first (just as if there were noparentheses at all). Generally speaking, adding parentheses in big expressions is agreat idea; it not only forces the evaluation order you want, but also aids readability.Mixed Types Are Converted UpBesides mixing operators in expressions, you can also mix numeric types. Forinstance, you can add an integer to a floating-point number:40 + 3.14But 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: inmixed-type expressions, <strong>Python</strong> first converts operands up to the type of the mostcomplicated operand, and then performs the math on same-type operands. If you’veused C, you’ll find this behavior similar to type conversions in that language.<strong>Python</strong> Expression Operators | 97

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

Saved successfully!

Ooh no, something went wrong!