"""Evaluating expressions. This file is not meant to be run as a script - cut and paste lines 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 # think of an expression as something that you can assign # or print # 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 # 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 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 # 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! # the exponentiation operator: 2**8