Книга: Fedora™ Unleashed, 2008 edition

Numbers

Numbers

The way Python handles numbers is more precise than some other languages. It has all the normal operators — such as + for addition, - for subtraction, / for division, and * for multiplication — but it adds % for modulus (division remainder), ** for raise to the power, and // for floor division. It is also very 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.0
>>> 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. Because b is converted 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 division— rounds 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?2?2?2?2? ...), and the second raises 2 to the power of 31. Notice how the second number has a capital L on the end of it — this 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 with simple instructions on the CPU, whereas long integers — because they can be as big as you need them to be — need to be calculated in software and therefore are slower.

When specifying big numbers, you need not put the L at the end — Python 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 by using typecasting, like this:

>>> num = 10
>>> int(num)
10
>>> float(num)
10.0
>>> long(num)
10L
>>> floatnum = 10.0
>>> int(floatnum)
10
>>> float(floatnum)
10.0
>>> long(floatnum)
10L

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.

Оглавление книги

Оглавление статьи/книги

Генерация: 0.072. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз