Python DATATYPES 02

Python DATATYPES


Print statement :

            The print() function prints the specified message to the screen, or other standard output device.
The message can be a string, or any other object, the object will be converted into a string before written to the screen.

Syntax: print('Hello world')| print("Hello world")

Datatype & Examples :

Standard Data Types :

             The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.
Python has five standard data types
  • Numbers ( int )
  • String ( str )
  • List ( list || [ ] )
  • Tuple ( " (" ," )" ) 
  • Dictionary ( { })
Supported Datatype 
  • Set
Number:
Python supports four different numerical types −
  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j

Strings:

            Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −
I/P

str = 'Hello World!'

print (str)                              # Prints complete string
print (str[0])                         # Prints first character of the string
print (str[2:5])                      # Prints characters starting from 3rd to 5th
print (str[2:] )                       # Prints string starting from 3rd character
print (str * 2 )                       # Prints string two times
print (str + "TEST")             # Prints concatenated string

O/P 
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Lists

Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −
I/P
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
a= [123, 'john']

print (list)                   # Prints complete list
print (list[0])              # Prints first element of the list
print (list[1:3])           # Prints elements starting from 2nd till 3rd 
print (list[2:])             # Prints elements starting from 3rd element
print (a * 2)                # Prints list two times
print (list + a)             # Prints concatenated lists
O/P
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example −
I/P:


tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
a= (123, 'john')

print (tuple)                  # Prints complete list
print (tuple[0])             # Prints first element of the list
print (tuple[1:3])          # Prints elements starting from 2nd till 3rd 
print (tuple[2:])            # Prints elements starting from 3rd element
print (a* 2)                   # Prints list two times
print (tuple + a)            # Prints concatenated lists
O/P:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Python Dictionary

Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −
I/P:
dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

a = {'name': 'john','code':6734, 'dept': 'sales'}


print (dict['one'])             # Prints value for 'one' key
print (dict[2])                  # Prints value for 2 key
print (a)                           # Prints complete dictionary
print (a.keys())                # Prints all the keys
print (a.values())             # Prints all the values
O/P:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']


Data Type Conversion

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.
Sr.No.Function & Description
1
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2
long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3
float(x)
Converts x to a floating-point number.
4
complex(real [,imag])
Creates a complex number.
5
str(x)
Converts object x to a string representation.
6
repr(x)
Converts object x to an expression string.
7
eval(str)
Evaluates a string and returns an object.
8
tuple(s)
Converts s to a tuple.
9
list(s)
Converts s to a list.
10
set(s)
Converts s to a set.
11
dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12
frozenset(s)
Converts s to a frozen set.
13
chr(x)
Converts an integer to a character.
14
unichr(x)
Converts an integer to a Unicode character.
15
ord(x)
Converts a single character to its integer value.
16
hex(x)
Converts an integer to a hexadecimal string.
17
oct(x)
Converts an integer to an octal string.

SET:
                     Mathematically a set is a collection of items not in any particular order. A Python set is similar to this mathematical definition with below additional conditions.
  • The elements in the set cannot be duplicates.
  • The elements in the set are immutable(cannot be modified) but the set as a whole is mutable.
  • There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.

Set Operations

The sets in python are typically used for mathematical operations like union, intersection, difference and complement etc. We can create a set, access it’s elements and carry out these mathematical operations as shown below.

Creating a set

A set is created by using the set() function or placing all the elements within a pair of curly braces.
 
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
 
When the above code is executed, it produces the following result. Please note how the order of the elements has changed in the result.
 
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
set(['Jan', 'Mar', 'Feb'])
set([17, 21, 22])
 

Accessing Values in a Set

We cannot access individual values in a set. We can only access all the elements together as shown above. But we can also get a list of individual elements by looping through the set.
 
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
 
for d in Days:
 print(d)
When the above code is executed, it produces the following result.
Wed
Sun
Fri
Tue
Mon
Thu
Sat

Adding Items to a Set

We can add elements to a set by using add() method. Again as discussed there is no specific index attached to the newly added element.
 
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
 
Days.add("Sun")
print(Days)
When the above code is executed, it produces the following result.
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Removing Item from a Set

We can remove elements from a set by using discard() method. Again as discussed there is no specific index attached to the newly added element.
 
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
 
Days.discard("Sun")
print(Days)
When the above code is executed, it produces the following result.
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Union of Sets

The union operation on two sets produces a new set containing all the distinct elements from both the sets. In the below example the element “Wed” is present in both the sets.
 
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print(AllDays)
When the above code is executed, it produces the following result. Please note the result has only one “wed”.
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Intersection of Sets

The intersection operation on two sets produces a new set containing only the common elements from both the sets. In the below example the element “Wed” is present in both the sets.
 
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)
When the above code is executed, it produces the following result. Please note the result has only one “wed”.
set(['Wed'])
 

Difference of Sets

The difference operation on two sets produces a new set containing only the elements from the first set and none from the second set. In the below example the element “Wed” is present in both the sets so it will not be found in the result set.
 
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)
When the above code is executed, it produces the following result. Please note the result has only one “wed”.
set(['Mon', 'Tue'])

Compare Sets

We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)
When the above code is executed, it produces the following result.

True
True

Ref             :  https://www.tutorialspoint.com, https://www.w3schools.com/



Comments

Popular posts from this blog

Python introduction 01