Using the Shell to Calculate Sums

You can also use the shell to carry out simple calculations. Table 12-1 shows you the different mathematical operators you can use in your sums. Just put the sum after the `print`

command, like this:

`>>> print 5+5`

`10`

`>>> print 9-4`

`5`

`>>> print 7*7`

`49`

`>>> print 10/2`

`5`

`>>> print “5+5”`

`5+5`

There are a few surprises in how division is carried out in Python. If you cast your mind back to your mathematics lessons, you might remember that whole numbers, which have no decimal portion, are called integers. In Python 2.7, if you divide an integer by an integer, you get an integer as a result, which means the answer can be less accurate than you might expect from a computer. For example, what’s 7 divided by 2?

`>>> print 7/2`

`3`

Close, but not close enough. To force Python to give you an answer that would pass a teacher’s scrutiny, add a decimal portion to one of the values in your sum, like this:

`>>> print 7/2.0`

`3.5`

`>>> print 7.0/2`

`3.5`

If you want to force the rounding effect to remove any decimal portion from your answer, you can use the `//`

(floor division) operator, like this:

`>>> print 10.0/3`

`3.33333333333`

`>>> print 10.0//3`

`3.0`

An operator you might not have come across before is modulo

Start Free Trial

No credit card required