## Numbers

The way Python handles numbers is more precise than some other languages. It has all the normal operatorssuch as + for addition, - for subtraction, / for division, and * for multiplicationbut it adds % for modulus (division remainder), ** for raise to the power, and // for floor division. It is also specific about which type of number is being used, as this example shows:

 >>> a = 5 >>> b = 10 >>> a * b 50 >>> a / b 0 >>> b = 10 >>> a / b 0.5 >>> a // b 0.0

The first division returns 0 because both a and b are integers (whole numbers), so Python calculates the division as an integer, giving 0. By converting b to 10.0, Python considers it to be a floating-point number, and so the division is now calculated as a floating-point value, giving 0.5. Even with b being floating point, using //floor divisionrounds it down.

Using **, you can easily see how Python works with integers:

>>> 2 ** 30 1073741824 >>> 2 ** 31 2147483648L

The first statement raises 2 to the power of 30 (that is, 2 x 2 x 2 x 2 x 2 x ...), and the second raises 2 to the power of 31. Notice how the second number has a capital L on the end of itthis is Python telling you that it is a long integer. The difference between long integers and normal integers is slight but important: Normal integers can be calculated using simple instructions on the CPU, whereas long integersbecause they can be as big as you need them to beneed to be calculated in software and therefore are slower.

When specifying big numbers, you need not put the L at the endPython figures it out for you. Furthermore, if a number starts off as a normal number and then exceeds its boundaries, Python automatically converts it to a long integer. The same is not true the other way around: If you have a long integer and then divide it by another number so that it could be stored as a normal integer, it remains a long integer:

>>> num = 999999999999999999999999999999999L >>> num = num / 1000000000000000000000000000000 >>> num 999L

You can convert between number types using typecasting, like this:

>>> floatnum = 10.0 >>> int(floatnum) 10

You need not worry whether you are using integers or long integers; Python handles it all for you, so you can concentrate on getting the code right.