12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.6. Expressions 132.6 ExpressionsAnexpressionisacombinationofvalues,variables,andoperators. Avalueallbyitselfisconsideredan expression, and so is a variable, so the following are all legal expressions (assuming that thevariablexhas been assigned avalue):17xx + 17Ifyou type an expression ininteractive mode, the interpreter evaluates itand displays the result:>>> 1 + 12Butinascript,anexpressionallbyitselfdoesn’tdoanything! Thisisacommonsourceofconfusionforbeginners.Exercise 2.2 Type thefollowing statements inthe<strong>Python</strong> interpreter toseewhat they do:5x = 5x + 1Now put the same statements into a script and run it. What is the output? Modify the script bytransformingeach expression into aprint statement and then run itagain.2.7 OrderofoperationsWhenmorethanoneoperatorappearsinanexpression,theorderofevaluationdependsontherulesofprecedence. Formathematicaloperators,<strong>Python</strong>followsmathematicalconvention. TheacronymPEMDAS isauseful way toremember therules:• Parentheseshavethehighestprecedenceandcanbeusedtoforceanexpressiontoevaluateinthe order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in(minute * 100) / 60,even ifitdoesn’t change the result.• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not27.• Multiplication and Division have the same precedence, which is higher than Addition andSubtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not5.• Operators with the same precedence are evaluated from left to right (except exponentiation).Sointheexpressiondegrees / 2 * pi,thedivisionhappensfirstandtheresultismultipliedbypi. To divide by2π, you can use parentheses or writedegrees / 2 / pi.

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

Saved successfully!

Ooh no, something went wrong!