What is Python Numbers ?

Python Numbers

There are three numeric types in Python Numbers:

  • int
  • float
  • Complex

Example

x = 1    # int

y = 2.8  # float

z = 1j   # complex

To verify the type of any object in Python, use the type() function:

Example

print(type(x))

print(type(y))

print(type(z))

Here are some examples of Python Numbers

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEL32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j

Note: While integers can be of any length, a floating-point number is accurate only up to 15 decimal places (the 16th place is inaccurate).

Python Number System

The numbers we deal with every day are of the decimal (base 10) number system. But computer programmers (generally embedded programmers) need to work with binary (base 2), hexadecimal (base 16) and octal (base 8) number systems.

In Python, we can represent these numbers by appropriately placing a prefix before that number. The following table lists these prefixes.

Number SystemPrefix
Binary‘0b’ or ‘0B’
Octal‘0o’ or ‘0O’
Hexadecimal‘0x’ or ‘0X’

Here are some examples

# Output: 107

print(0b1101011)

# Output: 253 (251 + 2)

print(0xFB + 0b10)

# Output: 13

print(0o15)

When you run the program, the output will be:

107

253

13

Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

Example

Convert from one type to another:

x = 1    # int

y = 2.8  # float

z = 1j   # complex

#convert from int to float:

a = float(x)

#convert from float to int:

b = int(y)

#convert from int to complex:

c = complex(x)

print(a)

print(b)

print(c)

print(type(a))

print(type(b))

print(type(c))

Note: You cannot convert complex numbers into another number type.

Leave a Reply