O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

remember.eps Note that you don’t use quotes around the sum in your print command. What would happen if you did? Python would put on the screen literally what you asked it to, like this:

>>> 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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required