Python Data Types
Definition
A datatype represents the type of data stored in computer memory or variable. The datatypes which are already available in Python are called Built-in datatypes, and that created by programmer is called User-defined datatype
Now we will study each datatype with examples.
Built-in Datatype
Their are 5 different types of Built-in datatype:
- None Type
- Numeric Types
- Sequence
- Sets
- Mapping
None Type
- The 'None' datatype in Python represents an object that does not contain any values. Same like 'null' in Java.
- In Python only one None object is provided.
- One of it's use is, it can be used inside function as a default value to arguments. While calling function no value is passed, then the default value taken is 'None'.
Numeric Types
The sub-Types of Numeric datatype is
- int (integer)
- float (decimal point number)
- complex (real and imaginary number)
- bool (Boolean)
Integer (int)
- As the name suggests the variable stores integer number (non decimal or non fractional), which is called as 'int'.
- Now assume you want to store number 10 in a variable 'x', then you can write x = 10 where x is variable (or identifier) which stores an integer number '10', so datatype of variable x becomes int.
- Their is no limit for the size of an int datatype in Python. It can store very large number.
float
- This datatype represents floating point number, i.e., decimal or fractional number.
- Taking an example, if you are storing y with a value of 2.5 like y = 2.5 then the data type of variable y becomes float and value stored in it is 2.5.
- The variable having data type as float can also store scientific notation like 'e' or 'E' to represents power of 10, which is called as 'exponential form' like 2.5 x 103 is written as 2.5e3 like y = 2.5e3 or y = 2.5E3, both are same.
- By using scientific notation a very big number can be stored in very small memory.
Complex
- A number written in the form of (a + bj) or (a + bJ) is called complex number, where a is real part and b is imaginary part, 'j' or 'J' represents square root (sqrt) value of -1.
- The part a and b may contain integer or float values like (1 + 2j) or (1 + 2.2J)
- For example, z = -1-5.6J Here, variable z is of complex type having real part as -1 and imaginary part as -5.6.
Now lets take an example with program to add two complex numbers.
![]() |
Program to add two complex number in Python |
![]() |
Result of Program to add two complex number in Python seen in Python shell |
Bool datatype
- This datatype represents Boolean values. There are only two Boolean values 'True' and 'False' represented by this type.
- Python internally represents True as 1 and False as 0.
- It is used in conditional situation.
- For example if you are finding greater number among two numbers then the program will be like x = 10 y = 5 if (x > y): print ("x is grater than y")
- Here Python will first store a values in variable x and y, than it will compare x with y and if x is greater than y it will pass True and execute the print command. And if it is False it will go to next instruction, which in this case is nothing.
Representing Binary, Octal and Hexadecimal Numbers
- Binary Number : It is represented as prefixing 0b (zero and b) or 0B (zero and B) before a value. For example 0b10110101 or 0B10110101.
- Hexadecimal Number : It is represented as prefixing 0x (zero and x) or 0X (zero and X) before a value. For example 0xA1B56 or 0XA1B56.
- Octal Number : It is represented as prefixing 0o (zero and o) or 0O (zero and O) before a value. For example 0o1234 or 0O1234.
Converting Datatypes
After knowing all the datatypes now we will see how to convert a value from one datatype to another with an simple example.
![]() |
Converting Datatype Program |
![]() |
Output for Converting Datatypes Program |
If you see above program different datatypes are stored in different variables namely n1, n2, n3 and they are converted into decimal or integer value by simply using 'int' instruction.
Their is another method to convert to convert the numbers is by using string and 'base' value. Now, 'base' here represents base of a number system. Like base 2 means binary number, base 8 means octal number, base 16 means hexadecimal number, and base 10 means decimal number.
Lets see how can you use this method to convert a number with same example as above.
![]() |
Converting datatype using int(string,base) |
Output:-
![]() |
Output for Converting Datatypes Program using int(string, base) |
Now, if you compare both the program you will find that variable n1, n2, n3 is not storing a number but a string. And string can also be used for converting from one datatype to another. We will see string in detail but, now just understand defining number in string format and using int(string,base) you can convert any datatype to decimal. Here, in 'int(string,base) ' base should be base of string, which is already cleared from program.
Sequence Datatype
A sequence is representation of group of datatypes or items or elements.
Let's take an example from above program, n1 = "1010" , here variable n1 is of string datatype and is a group of binary number.
Types of Sequence Datatype
- str (string)
- bytes
- bytearray
- list
- tuple
Str Datatype
A string is a represented by a group of characters or an array of character. They are enclosed in 'single quotes', "double quotes", """triple double quotes""", '''triple single quotes'''.
Let's take an example:
str1 = ' Hello There' # single quote
str2 = " Hello There" # double quote
str3 = """There are various animals in zoo like 'lion','tiger', 'beer', etc...""" #triple double quotes
Now, str1 and str2 are very easy to understand, what ever group of characters in 'single quotes', "double quotes" are saved in str1 and str2.
But, if you see str3, here we have use triple double quotes and single quotes too. This type of method is useful to embed a string inside another string.
The output of print(str3) will be: There are various animals in zoo like 'lion','tiger', 'beer', etc...
The slicing of string is also possible in Python. The slice operator is represented by square brackets [and] to retrieve pieces of string.
The character in the string is always counted from 0 (zero) onward. Hence str[0] represents 0th character of str variable, i.e., beginning of string.
For example:
S = 'Welcome to Pythonior' #This is original string
print(S)
Welcome to Pythonior #output
print(S[0]) #display 0th character
W #output
print(S[2:5]) #display 2nd to 4th character
elc #output
print(S[5: ]) #display from 5th till end
ome to Pythonior #output
print(S[-2]) #display second character from the end
o #output
byte Datatype
- It represents group of byte numbers just like array.
- A byte number is any positive number from 0 to 255.
- It cannot store negative number.
- We cannot modify or edit any element in byte type array.
Let's see an example
elements = [10 20 30 40 50] #list of byte numbers
x = bytes(elements) #convert the list into byte array
print(x[0]) # print 0th element
Output = 10
Now if you say,
x[0] = 02
This will give an error because you cannot replace any element from byte datatype.
Let's take another example:
#program for byte type array
#create a list of byte numbers.
elements = [10 20 30 40 50]
#convert the list into byte array
x = bytes(elements)
#retrieve elements from x using for loop and display
for i in x : print(i)
Output = 10
20
30
40
50
bytearray Datatype
- This is as byte type array.
- Only difference is it can be modified and byte type array cannot.
Let's see with an example
#program for bytearray type array
#create a list of byte numbers.
elements = [10 20 30 40 50]
#convert the list into byte array
x = bytes(elements)
#modify the elements
x[1] = 200
x[2] = 0
#retrieve elements from x using for loop and display
for i in x : print(i)
Output = 10
200
0
40
50
list Datatype
- It represents group of different type of elements.
- Difference between list and array is Array can store same type of elements, while list stores different type of elements.
Let's see some operation on list
![]() |
Some Operation on Lists |
tuple Datatype
- Tuple is similar to list.
- The elements in tuple are enclosed in Parentheses ( ), while elements in list are enclosed in square brackets [ ].
- Tuple cannot be modified as that of list.
- You can call tuple as read-only list.
Sets
- A set in Python is similar to that in mathematics. It is collection of unordered items. Every item in set is unique
- The elements in Sets are enclosed in curly braces { } and separated with coma. eg: A= {1,3,5}
- If you put same number in set twice it will be considered as one. B = {1,3,5,5}
Lets look at some of the basic operations in Sets
Union
- Consider to sets A and B, then Union of A and B (A U B) consist of all the elements from and set A and B.
- It uses | operator.
Example: A = {1,2,3}
B = {4,5,6}
print(A | B)
Output = {1,2,3,4,5}
Intersection
- It gives only common elements from both the sets.
- It uses & operator
Example: A = {1,2,3,4}
B = {3,4,5,6}
print(A & B)
Output = {3,4}
Difference
- (A-B) will give set of elements that are only in A and not in B.
- (B-A) will give set of elements that are only in B and not in A.
Example: A = {1,2,3,4}
B = {3,4,5,6}
print(A - B)
Output = {1,2}
Symmetric Difference
- It will give all the uncommon elements from both A and B sets.
- It uses ^ operator
Example: A = {1,2,3,4}
B = {3,4,5,6}
print(A ^ B)
Output = {1,2,5,6}
Mapping
- Mapping is also called as Dictionary.
Let me explain this with an example.
You all may know about PAN number, if anyone those who don't know what it is, it is nothing but Permanent Account Number given by Income Tax department of India to an Indian citizen.
I'll not go in detail about it.
So on every PAN you have an unique number and your name attached with that number.
Now, let's consider PAN number as a Key and person's name as Value attached to that Key.
Dictionary has these 'Key Value' pairs enclosed with { } and Key and values are separated with ':'.
Example:
Dict = {'Name' : 'Swapnil', 'PAN' : 'FDDPK129'}
print(Dict[Name])
Output = Swapnil
Want's to change the elements:
Dict = {'Name' : 'Swapnil', 'PAN' : 'FDDPK129'}
Dict ['Age'] = 29
Dict ['Occupation'] = 'Blogger'
Output = {'Name' = 'Swapnil', 'PAN' = 'FDDPK129', 'Age' = 29, 'Occupation' = 'Blogger'}
User-Defined Datatype
- The datatypes created by programmer is called User-defined datatype, like a class or a module. Which we will discuss in upcoming posts.
Hope you like this post, if you have any questions feel free to write me an email.
Thank You....
Comments
Post a Comment