Main.Expressions History

Hide minor edits - Show changes to markup

January 29, 2013, at 02:42 PM MST by 129.82.44.223 -
Changed line 6 from:

into the interpreter.

to:

lines into the interpreter.

Deleted lines 46-47:
  1. 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

  1. note that in Python 3.x the behavior of the division operator is different
  2. Let's try it out:

from __future__ import division 1 / 2

January 24, 2010, at 05:09 PM MST by 71.196.160.210 -
Added line 3:
Added lines 23-25:
  1. think of an expression as something that you can assign
  2. or print
January 24, 2010, at 05:07 PM MST by 71.196.160.210 -
Added lines 73-75:
  1. the exponentiation operator:

2**8

January 21, 2010, at 01:37 PM MST by 129.82.44.241 -
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. """

  1. an expression is something that the interpreter can evaluate
  2. We build expressions from simpler expressions.
  3. The basic building blocks are literals and identifiers:

17

"hello"

  1. if we define a variable, e.g.,

minutes = 59

  1. then the variable by itself is also an expression

minutes

  1. We can construct compound expressions by joining simpler
  2. expressions using operators:

17 + 42

"hello" + "hello"

  1. notice that the action of the operator depends on the operands:
  2. integer addition is not the same as string addition (concatenation).
  3. We can use the python interpreter to evaluate arithmetic expressions
  4. But the results are not necessarily what we would expect. For example

1 / 2

  1. The reason is that python performed integer division.
  2. You get a different result if you do

1.0 / 2

  1. note that in future Python versions this is going to change
  2. there is a truncating division operator that performs integer
  3. division:

1 // 2 1.0 // 2

  1. Recommendation: whenever you want integer division use //
  2. otherwise, make sure one of the operands is a floating point number

float(1) / 2

  1. you can print an expression:

hours = 11 minutes = 59 print "Number of minutes since midnight ", hours * 60 + minutes

  1. you can assign the result of an expression to a variable:

minutesSinceMidnight = hours * 60 + minutes

  1. operators have rules of precedence:

(1 + 2) * 3

  1. is not the same as

1 + 2 * 3

  1. when in doubt, use parentheses!

(:sourceend:)