Python Data Types


Out of the available data types in Python, we focus on the following most important types.

Integer(int)

Positive and negative whole numbers.

Float(float)

Positive and negative decimal numbers.

String(str)

Sequence of charachters.

List(list)

Items separated by commas and enclosed within square brackets - [ ].

Tuple(tuple)

Items separated by commas and enclosed within parenthesis - ().

Dictionary(dict)

Keys and values enclosed within curly brackets - { }.


"type" function


We can use the "type" keyword to check which data type does the perticular element belong to.

Press Run to get the data type of the follwing.

print (type(100)) print (type("hello world")) print (type(100.00))
Press Run to execute.

In the above example you can idetify that quotes are not used to declare integer or float types.

Basically anything within qutoes(double/single) are strings(str) in Python.

print (type("100")) print (type("hello world")) print (type("100.00"))
Press Run to execute.

Press Run to get the data type of the follwing.

print (type( ["hello","world"])) print (type( ("hello", "world"))) print (type( {"country":"sri lanka"}))
Press Run to execute.

You'll learn more about the above data types on Collection types lesson.


"isinstance" function


This function can be used to check a variable against a data type.

Press Run to check whether the data type matches the variable.

a = 100 b = "hello world" c = 100.00 #Correct types print(isinstance(a,int)) print(isinstance(b,str)) print(isinstance(c,float)) #wrong types print(isinstance(a,str)) print(isinstance(b,float)) print(isinstance(c,int))
Press Run to execute.

Type convertion


This method is used to convert a certain data type into another.

This method also have certain limitations as well.

Example

#convert integer to string
a = str(100)
#convert float to string
b = str(100.00)
#convert float to interger
c = int(100.5)

You can find more examples using above method in here.

We cannot convert string values with alphabetical letters to any other data type.

This will throw an error since we try to convert a string to a integer value.

#convert string to integer a = int("hello world")
Press Run to execute.




Concept & Design by Code94 Labs