NUMERIC TYPES IN PYTHON

WHAT ARE THE NUMERIC TYPES IN PYTHON?


NUMERIC DATA TYPES

Python uses following three types of numeric data types. type() function in Python is used to get data type of object.

Data TypeExamplesOutputDescription
intx=1 print(type(x))<class โ€˜intโ€™>Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
floatx = 3.5 print(type(x))<class โ€˜floatโ€™>floating point number is a number, positive or negative, containing one or more decimals.
complexx = 1j print(type(x))<class โ€˜complexโ€™>Complex numbers are written with a โ€œjโ€ as the imaginary part.

NUMERIC DATA TYPES

Type Conversion in Python

We can convert from one type to another with the int(), float(), and complex() functions as shown below:

int to float conversion in Python
x=1
a=float(x)
print(a)
print(type(a))

int to float conversion in Python

Output
1.0
<class โ€˜floatโ€™>

Output of int to float conversion in Python

float to int conversion in Python
x=3.5
a=int(x)
print(a)
print(type(a))

float to int conversion in Python

Output
3
<class โ€˜intโ€™>

Output of float to int conversion example in Python

int to complex conversion in Python
x=1
a=complex(x)
print(a)
print(type(a))

int to complex conversion in Python

Output
(1+0j)
<class โ€˜complexโ€™>

Output of int to complex conversion example in Python

Random Number in Python

Python uses a built-in module called random that can be used to make random numbers as shown below:

Example of Random Number generation in Python
import random  
print(random.randrange(1, 5))

import random will import random module.

random.randrange(1, 5) function will generate random number between 1 and 4.

Output will be any random number-

Output for Example of Random Number generation in Python
2

Posted

in

Tags:

Comments

Leave a Reply