2.3 Expressions

Here is another program:
print "2 + 2 is", 2+2
print "3 * 4 is", 3 * 4
print 100 - 1, " = 100 - 1"
print "(33 + 2) / 5 + 11.5 = ",(33 + 2) / 5 + 11.5

And here is the output when the program is run:

2 + 2 is 4
3 * 4 is 12
99  = 100 - 1
(33 + 2) / 5 + 11.5 =  18.5

As you can see Python can turn your thousand dollar computer into a 5 dollar calculator.

Python has six basic operations:

Notice that division follows the rule, if there are no decimals to start with, there will be no decimals to end with. The following program shows this:

print "14 / 3 = ",14 / 3
print "14 % 3 = ",14 % 3
print
print "14.0 / 3.0 =",14.0 / 3.0
print "14.0 % 3.0 =",14 % 3.0
print
print "14.0 / 3 =",14.0 / 3
print "14.0 % 3 =",14.0 % 3
print
print "14 / 3.0 =",14 / 3.0
print "14 % 3.0 =",14 % 3.0
print
With the output:
14 / 3 =  4
14 % 3 =  2

14.0 / 3.0 = 4.66666666667
14.0 % 3.0 = 2.0

14.0 / 3 = 4.66666666667
14.0 % 3 = 2.0

14 / 3.0 = 4.66666666667
14 % 3.0 = 2.0
Notice how Python gives different answers for some problems depending on whether or not there decimal values are used.

The order of operations is the same as in math class:

  1. parentheses ()
  2. exponents **
  3. multiplication *, division \, and remainder %
  4. addition + and subtraction -