Main.Expressions History
Hide minor edits - Show changes to markup
January 29, 2013, at 02:42 PM MST
by -
Changed line 6 from:
into the interpreter.
to:
lines into the interpreter.
Deleted lines 46-47:
- note that in future Python versions this is going to change
Changed lines 56-64 from:
float(1) / 2
to:
x = 1 y = 2 float(x) / y
- note that in Python 3.x the behavior of the division operator is different
- Let's try it out:
from __future__ import division 1 / 2
January 24, 2010, at 05:09 PM MST
by -
Added line 3:
Added lines 23-25:
- think of an expression as something that you can assign
- or print
January 24, 2010, at 05:07 PM MST
by -
Added lines 73-75:
- the exponentiation operator:
2**8
January 21, 2010, at 01:37 PM MST
by -
Added lines 1-74:
(:source lang=python:)
"""Evaluating expressions. This file is not meant to be run as a script - cut and paste into the interpreter. """
- an expression is something that the interpreter can evaluate
- We build expressions from simpler expressions.
- The basic building blocks are literals and identifiers:
17
"hello"
- if we define a variable, e.g.,
minutes = 59
- then the variable by itself is also an expression
minutes
- We can construct compound expressions by joining simpler
- expressions using operators:
17 + 42
"hello" + "hello"
- notice that the action of the operator depends on the operands:
- integer addition is not the same as string addition (concatenation).
- We can use the python interpreter to evaluate arithmetic expressions
- But the results are not necessarily what we would expect. For example
1 / 2
- The reason is that python performed integer division.
- You get a different result if you do
1.0 / 2
- note that in future Python versions this is going to change
- there is a truncating division operator that performs integer
- division:
1 // 2 1.0 // 2
- Recommendation: whenever you want integer division use //
- otherwise, make sure one of the operands is a floating point number
float(1) / 2
- you can print an expression:
hours = 11 minutes = 59 print "Number of minutes since midnight ", hours * 60 + minutes
- you can assign the result of an expression to a variable:
minutesSinceMidnight = hours * 60 + minutes
- operators have rules of precedence:
(1 + 2) * 3
- is not the same as
1 + 2 * 3
- when in doubt, use parentheses!
(:sourceend:)
