Monday 29 April 2019

5. Data types in python


1.   Data types in python
  • What is data type?
  • type() function
  • Different types of data types
  • Built-in data types
  • Numeric types
  • int data type
  • float data type
  • complex data type
  • bool data type (boolean data type)
  • None data type
  • Sequences in Python
  • str data type
  • bytes data type
  • bytearray data type
  • list data structure 
  • tuple data structure       
  • range data type
  • Accessing range values
  • set data structure
  • dictionary data structure
  • User defined data types
  • Converting from one data type into another data type.
  • Programs
5. Data types

What is the data type?
  • A data type represents the type of data stored into a variable or memory.
Program       print different kinds of variables
Name          demo1.py

                  emp_id=1
                  name=”Nireekshan”
                  salary=100.50
                 
                  print(“My employee id is: ”, emp_id)
                  print(“My name is: ”, name)
                  print(“My salary is: ”, salary)

Output
My employee id is:  1
My name is: Nireekshan
My salary is:  100.5

type() function
  • type() is an in-built or predefined function in python.
  • This is used to check type of the variables
Program       print different kinds of variables and checking their type
Name          demo2.py

                  emp_id=1
                  name=”Nireekshan”
                  salary=100.50
                 
                  print(“My employee id is: ”, emp_id)
                  print(“My name is: ”, name)
                  print(“My salary is: ”, salary)
        
                  print(“emp_id type is: ”, type(emp_id))
                  print(“name type is: ”, type(name))
                  print(“salary type is: ”, type(salary))

Output
My employee id is:  1
My name is:  nireekshan
My salary is:  100.5
emp_id type is:  <class 'int'>
name type is:  <class 'str'>
salary type is:  <class 'float'>

2 Different types of data types
  • There are two type of data types.
    • Built-in data types:
      • The data types which are already available in python are called built-in data types.
    • User-defined data types:
      • Data types which are created by the programmer.
1.Built-in data types
1.   Numeric types
o   int
o   float
o   complex
2.   bool (boolean type)
3.   None
4.   str
5.   bytes
6.   bytearray
7.   list
8.   set
9.   tuple
10.dict
11.range

1. Numeric types
  • The numeric types represent numbers, these are divided into three types,
    • int
    • float
    • complex
1.1 int data type
  • The int data type represents values or numbers without decimal values.
  • In python there is no limit for the int data type.
  • It can store very large values conveniently.
Program       To print integer value
Name          demo3.py

                  a=20
                  print(a)
                  print(type(a))

output
                20
                <class ‘int’>


Program       To print an integer value
Name          demo4.py

                  b=9999999999999999999
                  print(b)
                  print(type(b))
        
output
                 9999999999999999999
                 <class ‘int’>

Info:
  • In python 2nd version long data type was existing but in python 3rd version long data type was removed
2. float data type
  • The float data type represents a number with a decimal values.
Program       To print float value and data type
Name          demo5.py

         salary = 50.5
print(salary)
print(type(salary))

Output
                  50.5
<class 'float'>
  • floating point numbers can also be written in scientific notation.
Program       float values in exponential notation
Name          demo6.py

         a = 2e2
         b = 2E2
          c = 2e3

print(a)       # 200
print(b)       # 200
print(c)        # 2000
print(type(a))        # <class ‘float>

output
                  200
                  200
                  <class ‘float’>

  • e and E represent exponentiation.
  • where e and E to represent the power of 10.
  • For example
    • The number 2 * 102 is written as 2E2, such numbers are also treated as floating point numbers.
3. complex data type
  • The complex data type represents the numbers which is written in the form of,
    •  a + bj
    • a + bJ
    • a is representing a real part of number
    • b is representing an imaginary part of the number.
    • The suffix small j or upper J after b indicates the square root of -1.
    • The part ‘a’ and ‘b’ may contain integers or floats.
Program       print complex numbers
Name          demo7.py

a = 3+5j
b = 2-5.5j
c = 3+10.5j

print(a)
print(b)      
print(c)

print()

print(a+b)
print(b+c)
print(c+a)   
output
(3+5j)
(2-5.5j)
(3+10.5j)

(5-0.5j)
(5+5j)
(6+15.5j)

Make a note
  • If we compare two complex values with <, <=, >, >= operators then we will get TypeError
Program       comparing two complex numbers by using > symbol
Name          demo8.py

a = 2 + 1j
b = 100 + 10j
print(a>b)  

Error
                  TypeError: '>' not supported between instances of 'complex' and 'complex'

2. bool data type (boolean data type)
  • bool data type represents boolean values in python.
  • bool data type having only two values those are,
    • True
    • False
  • Python internally represents,
    • True as 1(one)
    • False as 0(zero)
  • An empty string (“ ”) represented as False.
Program       printing bool values
Name          demo9.py

a = True
b = False

print(a)
print(b)
print(a+a)
print(a+b)

output
                  True
False
2
1

3. None data type
  • None data type represents an object that does not contain any value.
  • If any object having no value, then we can assign that object with None type.
Program       printing None data type
Name          demo10.py

                  a = None
                  print(a)
                  print(type(a))

output
                  None
                  <class ‘NoneType’>

ü  If any function is not returning anything then that function can return None data type.
ü  In the below program, we have created one function and calling that function.
ü  If a function can contain a return statement, then that function calling we need to assign to a variable.
ü  This assigned variable holds return

ü  Program 1


ü  Program 2


ü  We will learn more about this, in the upcoming function chapter.

Program       A function return int data type  
Name          demo11.py

                  def balance():
                           print(“This function returns int data type”)
                           return 500

                  b = balance()
                  print(b)

Output
                  This function returns int data type
                  500

Sequences in Python
ü  Sequence means an object can store a group of values,
1.   str
2.   bytes
3.   bytearray
4.   list
5.   tuple
6.   range

1. str data type
ü  A group of characters enclosed within single quotes or double quotes or triple quotes is called as string.
ü  We will discuss more about in string chapter.

Program       printing string data type
Name          demo12.py

name1 = ‘nireekshan’                       
name2 = “nireekshan”                      
name3 = ‘’’ nireekshan ‘’’

print(name1)
print(name2)
print(name3)
Output
                  nireekshan
                  nireekshan
                  nireekshan

2. bytes data type
ü  bytes data type represents group of numbers just like an array
ü  bytes data type can store the values which are from 0 to 256.
ü  bytes data type cannot store negative numbers.
create byte data type
o   First, we need to create list.
o   The created list we need to pass to bytes() function as a parameter
ü  bytes data type is immutable means we cannot modify or change the bytes object.

Program       Creating bytes data type
Name          demo14.py

x = [10, 20, 100, 40, 15]
                  y = bytes(x)
                  print(type(y))

Output
                  <class 'bytes'>

Program       accessing bytes data type elements by using index
Name          demo15.py

x = [10, 20, 30, 40, 15]
                  y = bytes(x)
                  print(y[0])
                  print(y[1])
                  print(y[2])
                  print(y[3])
                  print(y[4])

Output
10
20
30
40
15

ü  We can iterate bytes values by using for loop.

Program       printing values from bytes data type
Name          demo16.py

x = [10, 20, 100, 40, 15]
                  y = bytes(x)
for a in y:
                           print(a)

output
                  10
                  20
                  100
                  40
                  15

Program       ValueError: bytes must be in range(0, 256)
Name          demo17.py

x = [10, 20, 300, 40, 15]
                  y = bytes(x)

Error
                  ValueError: bytes must be in range(0, 256)

Program       bytes data type is immutable
Name          demo18.py

x = [10, 20, 30, 40, 15]
                  y = bytes(x)
                  y[0] = 30

Error
TypeError: 'bytes' object does not support item assignment

3. bytearray data type
ü  bytearray is same as bytes data type, but bytearray is mutable means we can modify the content of bytearray data type.

creating bytearray type
o   First, we need to create list.
o   The created list we need to pass as bytearray() parameter

Program       creating bytearray data type
Name          demo19.py

x = [10, 20, 30, 40, 15]
                  y = bytearray(x)
                  print(type(y))

Output
                  <class 'bytearray'>

Program       accessing bytes data type elements by using index
Name          demo20.py

x = [10, 20, 30, 40, 15]
                  y = bytearray(x)
                  print(y[0])
                  print(y[1])
                  print(y[2])
                  print(y[3])
                  print(y[4])

Output
10
20
30
40
15

ü  We can iterate bytearray values by using for loop.

Program       printing values from bytearray data type by using for loop
Name          demo21.py

x = [10, 20, 30, 40, 15]
                  y = bytearray(x)
for a in y:
                           print(a)

Output
                  10
                  20
                  30
                  40
                  15

Program       bytearray data type is mutable
Name          demo22.py

x = [10, 20, 30, 40, 15]
                  y = bytearray(x)
print("Before modifying y[0] value: ", y[0])
y[0] = 30
print("After modifying y[0] value: ", y[0])

Output

before modifying y[0] value:  10
after modifying y[0] value:  30

4. list data structure       
ü  We can create list data structure by using square brackets []
ü  list can store different data types
ü  list is mutable.
ü  We will discuss more about in list chapter.

5. tuple data structure    
ü  We can create tuple data structure by using parenthesis ()
ü  tuple can store different data types.
ü  tuple is immutable.
ü  We will discuss more about in tuple chapter.

6. range data type
ü  We can create a range of values by using range() function
ü  The range datatype represents a sequence of numbers.
ü  range data type is immutable, means we cannot modify once it created.
ü  range data type values can be print by using for loop.

Program       creating a range of values 0 to 4 by using range() function
Name          demo23.py

a=range(5)
print(a)               
for x in a:
print(x)

Output
                  range(0, 5)
0
1
2
3
4

Make a note
ü  We can create a list of values with range data type

Program       Creating list of values
Name          demo24.py

a=list(range(1, 10))
print(a)

Output
                  [1, 2, 3, 4, 5, 6, 7, 8, 9]

Accessing range values
ü  By using index, we can access elements present in the range data type

Program       Access elements from range data type
Name          demo25.py

a=range(1, 10)              
print(a[0])
print(a[1])

output

1
2

ü  If we are trying to access range data type values in out of range then we will get error.

Program       Access elements from range data type
Name          demo26.py

a=range(1, 10)              
print(a[0])
print(a[20])

Error

IndexError: range object index out of range

7. set data structure
ü  We can create set data structure by using parenthesis symbols {}
ü  set can store same type and different type of elements
ü  We will learn more in set chapter  

8. dictionary data structure
ü  We can create dictionary type by using curly braces {}
ü  dict represents group of elements in the form of key value pairs like map.
ü  We will discuss more in dict chapter

User defined data types
ü  The datatype which are created by the programmers are called ‘user-defined’ datatypes, example is class, module, array etc
ü  We will discuss about in OOPS upcoming chapter.

Make a note
ü  In Python the following data types are considered as Fundamental Data types,
o   int 
o   float
o   complex
o   bool
o   str

Converting from one data type into another data type.
ü  Based on requirement developer can convert from one data type into another data type explicitly, this is called type conversion.
ü  Python provides in build functions to convert from one type to another type.

o   int()            :        convert from other type into int type               
o   float()         :        convert from other type into float type
o   complex()    :        convert from other type into complex type       
o   bool()          :        convert from other type into bool type    
o   str()            :        convert from other type into str type