Python - Data Type Numbers

Introduction

Numbers in Python support the normal mathematical operations.

The plus sign (+) performs addition, a star (*) is used for multiplication, and two stars (**) are used for exponentiation:

Demo

print(123 + 234)                    # Integer addition 
print(1.5 * 4)                      # Floating-point multiplication 
print( 2 ** 100)                    # 2 to the power 100, again
# ww w . j a va  2s .  c  om

Result

Python 3.X's integer type automatically provides extra precision for large numbers.

Python 2.X long integer type handles large numbers for the normal integer type.

The following code computes 2 to the power 1,000,000 as an integer in Python and check the number of digits in it.

Demo

print( len(str(2 ** 1000000)))       # How many digits in a really BIG number?

Result

Here, the code did a nested-call: first converting the ** result's number to a string of digits with the built-in str function, and then getting the length of the resulting string with len.

The end result is the number of digits.

str and len work on many object types.

Consider the following code

print( 3.1415 * 2)           # repr: as code (Pythons < 2.7 and 3.1) 
#6.2830000000000004 
print(3.1415 * 2)            # str: user-friendly 
#6.283 

The first result isn't a bug: it's only a display issue.

There are two ways to print every object in Python:

  • with full precision as in the first result shown here, and
  • in a user-friendly form as in the second.

Formally, the first form is known as an object's as-code repr, and the second is its user-friendly str.

In older Pythons, the floating-point repr sometimes displays more precision than you might expect.

In Python 2.7 and the latest 3.X, floating-point numbers display themselves more intelligently, usually with fewer extraneous digits.

Demo

print(3.1415 * 2)                   # repr: as code (Pythons >= 2.7 and 3.1)

Result

There are useful numeric modules that we import to use:

Demo

import math 
print(math.pi )
print(math.sqrt(85) )

Result

The math module contains more advanced numeric tools as functions.

The random module performs random-number generation and random selections:

Demo

import random 
print( random.random() )
print( random.choice([1, 2, 3, 4]) )

Result

Related Topics