EXACTLY WHAT ARE DATATYPE IN PYTHON? – 2

Datatypes in python Innovate yourself
0
0

OVERVIEW

In this post, you will learn,

  • What are datatype in python?
  • How do we use datatype in python?
  • Why don’t we declare the variables in python?
  • What exactly the datatype are used for in python?

Introduction

From the introduction of python blog, you must have learnt that python is an object oriented programming language. So every data in python has it’s own datatype because every data type in python are classes and variables are object(instance) of these classes.

DATATYPE IN PYTHON

There are various datatype in python. The important and the mostly used data types are listed below.

  • int (integer)
  • float (float/fractional)
  • str (String)
  • bool (Boolean)
  • list (List are mutable)
  • tuple (Tuple are immutable)
  • dict (dictionary)
  • set (Sets)

Now, let’s understand about the various data types with the respective examples:

Python Integer

These comes under the python numbers category. These are defined and identified by int class.

To check that to which class our data belongs to we use the inbuilt python function type(). Similarly, you can use the inbuilt function isinstance() to check whether an object belongs to a particular class or not.

Here are the examples for the integer type.

a=5
print("{} is of type {}".format(a,type(a).__name__))
Output:
5 is of type int
Python Float

These comes under the python numbers category. These are defined and identified by float class.

To check that to which class our data belongs to we use the inbuilt python function type(). Similarly, you can use the inbuilt function isinstance() to check whether an object belongs to a particular class or not.

Here are the examples for the float type.

a=5.5
print("{} is of type {}".format(a,type(a).__name__))
Output:
5.5 is of type float
Python String

String is a sequence of Unicode characters. These are defined and identified by str class. We can use either single quotes(‘ ‘) or double quotes(” “) to represent strings. We can also use triple quotes, (”’ or “””) to store the multiple line strings.

Here are the examples for the string type.

msg="This is a single line string"
print(msg)
msg='''This is a multiple line string.
here we can store the string data in multiple lines.'''
print(msg)
Output:
This is a single line string
This is a multiple line string.
here we can store the string data in multiple lines.

Python Boolean

We represent the boolean data with either True or False value. These are defined and identified by bool class.

Here are the examples for the boolean type.

b=True
print("{} is of type {}".format(b,type(b).__name__))
Output:
True is of type bool
Python List

List holds the items in the ordered sequence. This is one of most flexible and commonly used datatype in python. List can hold items to be of homogeneous as well as heterogeneous.

Initialization of list is really simple and straight forward. Enclose all the elements in square brackets([ ]) separated with comma( , ). You can initialization the list as shown below.

list1=[1,3.5,"Innovate Yourself"]

We can also use the square brackets for doing the slicing of various data types like list, tuple and string. For the slicing you can slice the data with respect to the index value and in python the index value starts from 0 if we start from the beginning and -1 if we start from the end.

print("list1[:2] =",list1[:2])
print("list1[2] =",list1[2])
print("list1[1] =", list1[1])
list1[1]=5.5
print("list1[1] =", list1[1])
Output:
list1[:2] = [1, 3.5]
list1[2] = Innovate Yourself
list1[1] = 3.5
list1[1] = 5.5

Python tuple

Tuple holds the items in the ordered sequence just like the list. The only difference between list and tuple is tuple are immutable. Tuple can hold items to be of homogeneous as well as heterogeneous.

Declaration of tuple is really simple and straight forward. Enclose all the elements in parentheses ( ) separated with comma( , ). Data stored to the tuple can’t be modified once created.

Tuples are usually faster than lists as they can’t be changed dynamically. Also, tuple are used to write-protect the data. You can initialization the tuple as shown below.

tuple1=(1,3.5,"Innovate Yourself")
print("tuple1[:2] =",tuple1[:2])
print("tuple1[2] =",tuple1[2])
print("tuple1[1] =", tuple1[1])
tuple1[1]=5.5
print("tuple1[1] =", tuple1[1])
Output:
tuple1[:2] = (1, 3.5)
tuple1[2] = Innovate Yourself
tuple1[1] = 3.5
Traceback (most recent call last):
  File "Test.py", line 162, in 
    tuple1[1]=5.5
TypeError: 'tuple' object does not support item assignment

Python Dictionary

Dictionary is an unordered collection of key-value pair. Generally we use dictionary when we have our data in bulk and it is difficult to identify and access the data with the index numbering. For retrieving data dictionaries are optimized. To retrieve the data we must know the unique key of the dictionary.

These are defined and identified by dict class. In python, we enclose the key:value pair in curly brackets { }. Data that you store in dictionary will be stored with respect to the key and you can have the unique keys only so that you can identify and retrieve the data based on those keys. Key and value also can be of any type.

>>> dictionary={'a':5,"b":5.6,3:'Ashish'}
>>> print("Data stored is of type",type(dictionary).__name__)
Data stored is of type dict
dictionary={'a':5,"b":5.6,3:'Ashish'}
print(type(dictionary))
print(dictionary['a'])
print(dictionary[3])
print(dictionary[5])
Output:
5
Ashish
Traceback (most recent call last):
  File "Test.py", line 162, in 
    print(dictionary[5])
KeyError: 5
Python Sets

Set is an unordered collection of unique elements. Sets are defined just like the tuple and list, separated with comma ( , ). These are defined and identified by set class. The homogeneous or heterogeneous data is stored inside the curly brackets( { } ).

b = {5,2,3,1,4,2,3,4,3,5,1,1,2,2,3,4}

# printing set variable
print("b = ", b)

# data type of variable a
print(type(b))
Output:
b =  {1, 2, 3, 4, 5} 
<class 'set'>

Set are unordered collection, indexing has no meaning. Therefore, the slicing operator [] does not work.

>>> b = {1,2,3} 
>>> b[1] 
Traceback (most recent call last):   
  File "<string>", line 301, in runcode   
  File "<interactive input>", line 1, in <module> 
TypeError: 'set' object does not support indexing

For more clarification on datatype in python check our video here,

Why don’t we declare the variables in python?

The reason to this question is that every data is uniquely defined and identified with a particular class. So, every data is directly understood and return a type with respect to the class on checking. So we don’t have to declare the variable and we directly initialize it.

What exactly the datatype are used for in python?

Now the next question comes here is that if we don’t use datatype in python for the declaration then why exactly we have the keyword defined for every datatype in python? The answer to this question is that we use the datatype in python for the type casting or in general terms you can say for type conversion. Which means converting one datatype to the other datatype in python. The examples are given below to understand this in details.

a,b,c='4','5.5',5.6
print(type(a))
print(type(b))
print(type(c))
a,b,c=int(a),float(b),int(c)
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'str'>
<class 'str'>
<class 'float'>
<class 'int'>
<class 'float'>
<class 'int'>
datatype in python
type casting with datatype in python

For more clarification typecasting with datatype in python, check our video here,

Time to wrap up now. Hope you liked our content on datatype in python. See you in our next blog, thanks for reading our blog and do leave a comment below to help us improve the content to serve you all of our experience with you. Stay tuned with us for more python programming contents.

Also check out our other playlist Rasa Chatbot, Internet of things, Docker, etc.
Become a member of our social family on youtube here.

Leave a Reply