Python Numbers | Integers | Float | Complex Number

Advertisement

In this article we will explore Python Numbers Data Type with multiple examples:

 

1. Python Numbers Data Type

Python Numbers is one of the supported data types. Python treats numbers in several different ways, depending on how they’re being used. There are basically three different numeric types in Python explained below with their definition:

  • Integers (int) : These are the whole number which can be either a positive or negative number or zero (0)
  • Floating Numbers (float): These are numbers which contain a floating decimal point. They can be a positive or a negative value with one or more decimal points.
  • Complex Numbers (complex):These are an extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part.

 

2. Python Integers

Integers are whole numbers i.e. no fractions, no decimal points, nothing fancy. Well, aside from a possible initial sign. And bases, if you want to express numbers in other ways than the usual decimal (base 10).

 

2.1 Literal Integers

Any sequence of digits in Python represents a literal integer: Following is an example script with some valid integers:

#!/usr/bin/env python3

print(5)   ## Valid Integer
print(0)   ## Valid Integer
print(-10) ## Valid Integer (Negative values are allowed in an integer)
print(1_00_000) ## Valid Integer (Underscores are allowed in an integer as they are ignored)

# Print data type
print(type(5))
print(type(0))
print(type(-10))
print(type(1_00_000))

The output from this script:

~]# python3 example-1.py
5
0
-10
100000
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

Following are some examples with some invalid integers:

An integer cannot start with “0“:

Advertisement
#!/usr/bin/env python3

# Integer cannot start with zero (0) followed by digit (0-9)
print(05) # Invalid

Output from this script:

~]# python3 example-1.py
  File "example-1.py", line 4
    print(05) # Invalid
           ^
SyntaxError: invalid token

You cannot add commas in the integers:

#!/usr/bin/env python3

num = 1,00,000
print(num)
print(type(num))

Output from this script:

~]# python3 example-1.py
(1, 0, 0)
<class 'tuple'>

 

2.2 Bases

Integers are assumed to be decimal (base 10) unless you use a prefix to specify another base. You might never need to use these other bases, but you’ll probably see them in Python code somewhere, sometime.

In Python, you can express literal integers in three bases besides decimal with these integer prefixes:

  • 0b or 0B for binary (base 2)
  • 0o or 0O for octal (base 8)
  • 0x or 0X for hex (base 16)

These bases are all powers of two, and are handy in some cases, although you may never need to use anything other than good old decimal integers.

For example:

#!/usr/bin/env python3

value=0b10
print(value, type(value) )

Output from this script:

Advertisement
~]# python3 example-1.py
2 <class 'int'>

 

2.3 Convert Integer to any Base type

We can also convert any integer to any of the base type, following is an example script:

#!/usr/bin/env python3

value = 65
print(bin(value)) # Binary Format (Output would be 0b1000001)
print(oct(value)) # Octal Format (Output would be 0o101)
print(hex(value)) # Hexadecimal Format (Output would be 0x41)

Output from this script:

~]# python3 example-1.py
0b1000001
0o101
0x41

 

2.4 Type Conversions

You can use int() function to change different data type to integer. The int() function takes one input argument and returns one value, the integerized equivalent of the input argument. This will keep the whole number and discard any fractional part.

Sample Script:

#!/usr/bin/env python3

# Convert Boolean to Integer
print('True', ":", int(True))
print('False', ":", int(False))

# Convert Floating Number to Integer
print('Float', ":", int(98.6))
print('Float', ":", int(1.0e4))

# Convert nondecimal integers
print('Binary', ":", int('10', 2))
print('Octal', ":", int('10', 8))
print('Hexadecimal', ":", int('10', 16))

Output from this script:
Python Numbers | Integers | Float | Complex Number

You can also convert a string if it contains a numerical value “only”. For example:

#!/usr/bin/env python3

mystring = '10'
print(type(mystring))
print(int(mystring), ":", type(int(mystring)))

Output from this script:

~]# python3 example-2.py
<class 'str'>
10 : <class 'int'>

But if you have an integer that doesn’t looks like a number then you will get an exception:

#!/usr/bin/env python3

mystring = '10 is an integer'
print(type(mystring))
print(int(mystring), ":", type(int(mystring)))

Output from this script:

 ~]# python3 example-2.py
<class 'str'>
Traceback (most recent call last):
  File "example-2.py", line 5, in <module>
    print(int(mystring), ":", type(int(mystring)))
ValueError: invalid literal for int() with base 10: '10 is an integer'

 

2.5 How big can be an Integer?

In Python 2, the size of an int could be limited to 32 or 64 bits, depending on your CPU; 32 bits can store store any integer from –2,147,483,648 to 2,147,483,647. A long had 64 bits, allowing values from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Advertisement

In Python 3, the long type is long gone, and an int can be any size—even greater than 64 bits.

>>> print(10**100)
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

 

3. Python Floats

Integers are whole numbers, but floating-point numbers (called floats in Python) have decimal points. Here are some examples:

#!/usr/bin/env python3

float1 = 10.
float2 = 10.0
float3 = 010.0

print(type(float1))
print(type(float2))
print(type(float3))

Output from this script:
Python Numbers | Integers | Float | Complex Number

Floats can also include a decimal integer exponent after the letter e, following is an example script:

#!/usr/bin/env python3

float1 = 10e0
float2 = 5e1
float3 = 5.0e1

print(float1, "-", type(float1))
print(float2, "-", type(float2))
print(float3, "-", type(float3))

Output:
Python Numbers | Integers | Float | Complex Number

We can also use underscores in a float number:

#!/usr/bin/env python3

float1 = 1_00_000.0
print(float1, "-", type(float1))

Output from this script:

 ~]# python3 example-3.py
100000.0 - <class 'float'>

 

3.1 Type Conversions

You can use float() function to convert different data type to floats. Following example converts different data types such as string and integer into float:

#!/usr/bin/env python3

int1 = 10
int2 = -10
str1 = '20'

print('Boolean(True)', "-", float(True))
print('Boolean(False)', "-", float(False))
print('int1 - ', float(int1), type(float(int1)))
print('int2 - ', float(int2), type(float(int2)))
print('str1 - ', float(str1), type(float(str1)))

Output from this script:
Python Numbers | Integers | Float | Complex Number

But if your string contains more than an integer, then type conversion will raise ValueError:

#!/usr/bin/env python3

str1 = '20 is an integer'
print(float(str1))

Output from this script:

~]# python3 example-3.py
Traceback (most recent call last):
  File "example-3.py", line 4, in 
    print(float(str1))
ValueError: could not convert string to float: '20 is an integer'

 

4. Python Complex Numbers

Complex numbers are fully supported in the base Python language, which can be specified using the complex(real, imag) function or by floating-point numbers with a j suffix.

>>> # a real number
... 5
5
>>> # an imaginary number
... 8j
8j
>>> # an imaginary number
... 3 + 2j
(3+2j)

The real, imaginary, and conjugate values are easy to obtain, as shown here:

#!/usr/bin/env python3

val = complex(2, 4)
print(val.real)
print(val.imag)
print(val.conjugate())

Output from the script:

 ~]# python3 example-4.py
2.0
4.0
(2-4j)

We can also perform mathematical operation using complex number:

#!/usr/bin/env python3

val1 = complex(2, 4)
val2 = 3 - 5j

print(val1 + val2)
print(val1 * val2)
print(val1 / val2)

Output from this script:
Python Numbers | Integers | Float | Complex Number

 

Summary

In this article we learned about different Python Numbers data types such as Integers, Floats and Complex Numbers with different examples. We also learned ways to convert a data type into another using different function such as float() or int(). Although such type conversion has it’s own limitation and must be used properly to avoid any exceptions and ValueError.

 

Further Readings

Numeric Types — int, float, complex

 

Related Searches: Python init number, Python integer, Python numbers, What is a integer in python, numbers in python, integer python definition, example of integer in python, num in python, numbers in python programming, init in python example, python init example, python integer definition, define integer python

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment