In the last section, you were introduced to two different data types:

integers int() and strings str()

It will not surprise you to learn that Python has some other data types especially for dealing with numbers.

Python as a Calculator - Integers and Floats

Python can be used as a calculator in interactive mode.  Try typing in each of the following in the IDLE window:

1+1
8-6
2*4
-2+6
10/5

Now for a surprise!  Try 7/2

Maybe Python is not as smart a calculator as we first thought.

 
Python has a number of different ways of representing and storing data.  Numbers can be common integers or what is known as floats. Integers are whole numbers, but floats have decimal points.  3  7  25 are integers, 2.3   5.76   0.4 are floats.

To tell Python we want to use a float we use a decimal point in the number.  So 5 and 10 are both integers, but 5. and 10.0 are floats.  

If any number in a calculation is a float, Python will give you a float as an answer.

If the numbers are all integers, Python will give you an integer (whole number) answer.

So now try 7./2

Maybe Python is a bit smarter than it seemed!

Powers

The power operator is **

To write 2 to the power of 3, type it as 2**3

Longs

Integers have a maximum and minimum value because of the way the data is stored.  It is very large, but will vary depending on the type of computer you are using.  Longs are indicated with L at the end.

To see a long, try typing 2**100   

Now try 2**1000   (The answer is a very big number!)

Modulus

Modulus is another useful mathematical operation.  It gives the remainder from a division. 

Try 13%5, 6%2, 6%5

Here is an example program that uses the modulus operation to find the greatest common factor of two numbers. Note the use of abs to get the absolute value in case the numbers are negative eg abs(-5)=5

Type it in IDLE and test it:

 

Sum of Squares or Square of Sum?

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

This program will do the calculation and print out the answer:

Look at the program carefully and try to see how it works.  Note how the loop has range(1,11)  This means to start with value 1, then count up to, but not including, 11.  So it will count from 1 to 10.  (If you just put range(10), you would get values for range starting at 0 and going up to 9)

Your job is to modify the program to find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.  (If your program is correct, you should get 25164150)