Let's learn Data types in Python

Hello Guys, Welcome to Python series for Data Science - Basic to Advanced level

Let's learn Data types in Python

Why do we need to know Datatypes in Python?

The 3 most important things are always keeping in mind using python First, it is Case sensitive, second, is indentation problem, and third is data types We can perform operations only on the same data type variables if they are not the same types then we use type-casting and make them into similar data types.

Let's dive into the concepts of data types.

Datatypes

We can understand data types are the classification or categorization of data items. Since everything is an object in Python programming, data types are actually classes and variables are objects of these classes and we can determine data items by using the type() function.

Types of Data types

There are 2 types :

1. Primitive Datatypes(Immutable): These are the building blocks of data manipulation and have the property of immutable, which means the original value of items doesn't change.

a) Numeric - Integer, Float, Complex b) Text - Strings c) Boolean - True, False

2. Non-Primitive Data types(Mutable) - They are acted as a container when we want to store large numbers of heterogeneous or homogenous primitive datatype values then we use the following classes as given below.

i) List [], ii) Tuple (), iii) Set {}, iv) Dictionary {Key:Value}

These classes possess the mutable quality except tuples, which means the original data can be changed by using index numbers.

Practical Implementation of Primitive Datatype in one of the Python IDEs, Jupyter Notebook :

1. Integer Data Type: In this type, we take up the whole number, and it can be of any length.

Input

#Integer values always take whole values
value_1 = int(input('Enter first whole number:'))
value_2 = int(input('Enter second whole number:'))
add = value_1 + value_2
# print() gives permanent output
print('Addition of 2 integer value {} and {} is {}'.format(value_1,value_2,add))
# # type() tells in which class a variable belongs to
print(add,'is type of', type(add))

Output

Enter first whole number:8500
Enter second whole number:1200
The addition of 2 integer value 8500 and 1200 is 9700
9700 is type of <class 'int'>

2. Float data type - In this type, we take up decimal values and give accurate values up to 15 decimal places.

Input

a = 12.1564897123654789
print(a,'is a decimal value upto place 15')
print(a,'is a type of',type(a))
# isinstance() tells particular value belongs to that class or not
print(a,'is float number? ',isinstance(a,float))

Output

12.15648971236548 is a decimal value up to place 15
12.15648971236548 is a type of <class 'float'>
12.15648971236548 is the float number?  True
 we can see in our float number as 9 is truncated

3. Complex Data type: Complex numbers make with the real and the imaginary parts i.e a+bj. For the imaginary part, we use 'j' in python.

Input

num = 12 + 4j
print(num,'is belong to',type(num))
print(num,'is a complex number?', isinstance(num,complex))

Output

(12+4j) is belong to <class 'complex'>
(12+4j) is a complex number? True

4. Boolean Data Type: It always takes up True(1) or False(0) values and gives output either 1 or 0. Let's see by the example

Input

a = True
b = False
print(a,b,'belong to',type(a),type(b))
print('sum and multiplication of boolean values {},{}  are : '.format(a,b),a+b,'and',a*b)
print('Type of sum and multiplication is',type(a+b),type(a*b))

Output

True False belong to <class 'bool'> <class 'bool'>
sum and multiplication of boolean values True,False  are :  1 and 0
Type of sum and multiplication is <class 'int'> <class 'int'>
here we can see class of sum and multiplication is integer.

5. String Data Type:String literals can be defined with any of single quotes ('), double quotes (") or triple quotes (''' or """). All give the same result with two important differences.

If you quote with single quotes, you do not have to escape double quotes and vice-versa. If you quote with triple quotes, your string can span multiple lines

Input

string = 'Hello Python'
print(string,'belongs to',type(string))

# Parsing the string by using index number
print('First letter of word =',string[0])

#start(0) :end(5-1) : step size(2) always exclude upper bound means gives output till index no:UB-1
print('Desired result with step size 2 =',string[0:5:2])

# Reverse the string
print('Reverse the given string = ', string[::-1])

# multiple lines
"""print("fsdfsdfs)
(FsdfsfsFSDFSAFASFASDDF)
(sdfsfsdf")"""

Output

Hello Python belongs to <class 'str'>
The first letter of word = H
The desired result with step size 2 = Hlo
Reverse the given string =  nohtyP olleH
'print("fsdfsdfs)\n(FsdfsfsFSDFSAFASFASDDF)\n(sdfsfsdf")'

String possess immutable quality. Immutable means we cannot change the original value of an object by using the index. Have a look at the given example

Input

string[0]='l'

Output

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-b92d8add3c1a> in <module>
----> 1 string[0]='l'

TypeError: 'str' object does not support item assignment

Python provides so many in-built methods for string class. Have a look below by just using the object.tab key and find many methods.

tab.jpg

Python also provides docstring we can use it by simply pressingshift+tab key

doc.jpg

  • We can perform all arithmetic operations on the same data types as above mentioned but what if in case of adding a string with an integer, is it possible ?? Let's see by the example and try to understand

Input

print(10 + 'rs')

# Convert integer into string using single quotes
print('add string with integer =','10'+'rs')

# Another way to convert int into the string using the keyword 'str'
print('2nd way to write',str(10)+'rs')

# float to integer also vice-versa using keywords 'int','float'

a = 15
print('convert integer to float-',float(a))

b = 18.5
print('convert float to integer-',int(b))

'''Original values of a and b didn't change after the conversion
 so we can say integers,floats is also immutable data types'''

print("Get values of a and b",a,b)

Output

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-dcf139eb9f64> in <module>
----> 1 10 + 'rs'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

add string with integer = 10rs
2nd way to write 10rs
convert integer to float- 15.0
convert float to integer- 18
15 18.5

We cannot convert a string into a numeric form but the reverse can be possible.

From the above example, we can say Yes, we can add different datatypes by converting one into another and this conversion is known as Type-casting in python.

Thanking you, I hope it will be helpful to those who are complete beginners in this programming language. To know about the non-primitive datatypes stay tuned with me.