Datatypes
Datatype
It is a keyword that is used to specify the type of the data that a variable can hold in its memory space.
primitive datatypes of python:
int
float
complex
bool
sequence datatypes of python:
str
list
tuple
set
dict
In python, the datatype of the variable will be assumed implicitly based on the type of the value that is assigning from right hand side.
type() is a pre-defined function that returns the datatype of a variable
#Example
x=10
print(type(x)) #output: <class 'int'>
#Example
x=2.34
print(type(x)) #output: <class 'float'>
#Example
a="best computers"
print(type(a)) #output: <class 'str'>
#Example
a={2,4,6}
print(type(a)) #output: <class 'set'>
Python is dynamically typed language means the datatype of variable can be changed just with simple assignment statement. This is not possible in other statically typed languages like C,C++,Java etc.
#Example
num=12
print(type(num))
num=12.45
print(type(num))
num=True
print(type(num))
num=3+4j
print(type(num))
num="best"
print(type(num))
num=[2,4,6,8,10]
print(type(num))
num=(2,4,6,8,10)
print(type(num))
num={2,4,6,8,10}
print(type(num))
num={1:2,2:4,3:6,4:8,5:10}
print(type(num))
We will learn about sequence datatypes more in detail later.
We can also create a variable with the datatype as function too.
This is also called as explicit type casting or type conversion.
#Example
x=int()
print(type(x))
x=int(10) #x=10
print(type(x))
x="10"
print(type(x))
x=int("10") #type conversion
print(type(x))
x=int("B") #gives Error since incompatiable data is passed for conversion