PYTHON DATATYPES CPS 6195 Presented by Mirza Elahi
PYTHON DATATYPES CPS 6195 Presented by Mirza Elahi 10/29/2018
Outline q. Python Datatypes § Numbers § List § Tuple § String § Set § Dictionary § Nested Dictionary § Arrays § Matrix § List Comprehension
Number Data Type § 3 different class, int, float, complex § Functions, type(), isinstance() int(5. 3) >>>5 int(-5. 3) >>>-5 float(2) >>>2. 0 complex(‘ 7+11 j’) >>>(7+11 j) print(1 + 2. 0) >>>3. 0 a = 1 b = 2. 0 c = 7 + 11 j print(type(a)) print(type(b)) print(type(c)) print(isinstance(c, complex))
Number System § § Decimal, base 10 Binary, base 2 Hexadecimal, base 16 Octal, base 8 print(0 b 1101011) 107 print(0 x. FB + 0 b 10) 253 (251 + 2) print(0 o 15) 13
Type Conversion § Decimal (1. 1 + 2. 2) == 3. 3 >>>False print(1. 1 + 2. 2) >>>3. 300000003 from decimal import Decimal as D print(D('1. 1') + D('2. 2’)) >>>3. 3 • Fractions import fractions print(fractions. Fraction(1. 5)) >>>3/2 print(fractions. Fraction(1, 3)) >>>1/3 print(fractions. Fraction('1. 1’)) >>>11/10 from fractions import Fraction as F print(F(1, 3) + F(1, 3)) >>>2/3
Mathematics § math import math print(math. pi) 3. 141592653589793 print(math. cos(math. pi)) -1. 0 § Rand import random print(random()) print(random. randrange(1, 10)) x = ['a', 'b', 'c', 'd', 'e'] print(random. choice(x)) random. shuffle(x) print(x)
List § Create List cps =[“utep”, [2, 0, 1, 8], [‘z’]] § Access elements print(cps[0][1]) print(cps[1][2]) print(cps[-1]) § Slice list cps = [1, 3, 9] print(cps[: ]) print(cps[1: 2]) § Add / change elements cps[2: 2] = [5, 7] § Remove elements del cps[0: 1] § List methods list. method() print(cps. count(2))
List Comprehension § List comprehension cps =[2 ** x for x in range(10)] cps =[] For x in range(10): cps. append(2 ** x) cps =[2 ** x for x in range(10) if x>5] cps =[2 ** x for x in range(10) if x%2 == 1] § Built in list functions
Tuple § Similar to a list but the elements in a tuple cannot be changed. § Used for heterogeneous datatypes, key for a dictionary, performance boost. § Create tuple cps = (1, 2, 3) cps = (2018, “utep”, 1. 1) cps = (“utep”, [2 3 5], (1, 2, 3)) cps = 1, 2, 3, “utep” § One element tuple cps = (”utep", ) print(type(cps))
Access, Change & Delete Elements • Indexing cps= ( ‘u’, ‘t’, ‘e’, ‘p’) print(cps[0]) print(cps[-1]) print(cps[1: 2]) n_cps = (“utep”, [1 2 3], (4 5 6)) print(n_cps[0][4]) • Changing tuple n_cps[2][0] = 7 print(n_cps) print((1, 2, 3) + (4, 5, 6)) print((”utep", ) * 3) • Deleting Tuple del cps • Tuple Methods cps= (‘d’, ’e’, ’l’, ’e’, ’t’, ’e’, ) print(cps. count(‘e')) print(cps. index(‘l'))
Other Operations • Membership test using ‘in’ cps= ( ‘u’, ‘t’, ‘e’, ‘p’) print(‘u’ in cps) print(‘a’ in cps) • Iteration for program in (‘Math’, ’CPS'): print(”Utep", program)
String § String is sequence of characters. § Characters are encoded with 0’s and 1’s by the computer. § Python uses Unicode. § Create String § Indexing, Slicing cps = ‘Utep’ cps = “Utep” cps = ’’’Utep’’’ cps = “““Hello, welcome to the CPS program””” cps = ‘cps 2018' print('cps = ', cps) print('cps[0] = ', cps[0]) print('cps[-1] = ', cps[-1]) print('cps[1: 5] = ', cps[1: 5]) print('cps[2: -2] = ', cps[2: 2])
Operations § Elements of string cannot be changed but can be reassigned to the same name. cps = ‘Utep 2018’ cps[-1] = ‘ 7’ cps = ‘Welcome’ del cps[1] del cps § Membership Test using ‘in’ ‘u’ in ‘utep’ ‘t’ not in ‘utep’ § Concatenation cps 1 = ‘Utep’ cps 2 = ‘ 2018’ print(‘cps 1+cps 2=’, cps 1 + cps 2) Print(‘cps 1 * 3=’, cps 1*3) § Iteration count = 0 for letter in ‘utep cps': if(letter == ‘p'): count += 1 print(count, 'letters found')
More Operations § Built in functions cps = ‘utep' list_enumerate = list(enumerate(cps)) print('list(enumerate(cps) = ', list_enumerate) print('len(cps) = ', len(cps))
String Formatting He said, "What's there? " # using triple quotes print('''He said, "What's there? "''') # escaping single quotes print('He said, "What's there? "') # escaping double quotes print("He said, "What's there? "")
Set § Set is an unordered collection of items. § Set is mutable, meaning items can be added or removed. § Mathematical operations like union, intersection, symmetric difference can be carried out. § Create Set cps= {6, 1, 9, 5} cps = {1. 0, “Utep”, (1, 2, 3)} cps= set([1, 2, 3, 2]) print(cps) *no duplicates § Empty Set a = {} a = set() print(type(a))
Change & Remove Elements § Change cps = {0, 1} cps. add(2) cps. update([2, 3, 4]) cps. update([4, 5], {1, 6, 9}) print(cps) {0, 1, 2, 3, 4, 5, 6, 9} § Remove Elements cps = {1, 3, 5, 7, 9} cps. discard(3) cps. remove(7) print(cps) {1, 5, 9} *remove(8) will cause an error. cps = set("Hello. World") print(cps. pop()) >>>W print(cps. clear()) >>>None
Set Operations § Union A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A | B) A. union(B) B. union(A) >>>{1, 2, 3, 4, 5, 6, 7, 8} § Intersection Print(A & B) A. intersection(B) B. intersection(A) >>>{4, 5} § Difference or Only Print(A – B) A. difference(B) >>>{1, 2, 3} Print(B - A) B. difference(A) >>>{6, 7, 8} § Symmetric Difference print(A ^ B) A. symmetric_difference(B) B. symmetric_difference(A) >>> {1, 2, 3, 6, 7, 8}
Set Methods § Set Membership Test cps = set(“Utep”) Print(‘U’ in cps) >>>True Print(‘p’ not in cps) >>>False
Frozenset § Immutable sets, meaning elements cannot be changed. § Can be used as dictionary keys unlike sets. A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) A. isdisjoint(B) >>>False A. difference(B) >>>frozenset({1, 2})
Q&A
Quiz 1. Can you change items in tuple? Yes or No. cps_t = (1, 2, 3, [9, 8]) cps_t[1] = 7 (element cannot be changed) cps_t[3][0] = 7 (item of mutable element can be changed)
Quiz 2. Can you change the elements of a string? Yes or No. >>> cps = 'programiz’ >>> cps[5] = ‘a’. . . Type. Error: 'str' object does not support item assignment >>> cps = 'Python’ >>> cps 'Python' 3. Can we access index using any range or decimal number? Yes or No. >>> cps[15]. . . Index. Error: string index out of range integer >>> cps[1. 5]. . . Type. Error: string indices must be integers
Quiz 4. Can sets produce duplicates? Yes or no. >>>cps_set= {1, 2, 3, 4, 3, 2} >>>print(cps_set) {1, 2, 3, 4} # set do not have duplicates >>>cps_set = {1, 2, [3, 4]} Type. Error: unhashable type: 'list' # set cannot have mutable items # here [3, 4] is a mutable list # this will cause an error. 5. Can you remove elements not present in a set? cps = {1, 3, 4} cps. remove(2) Error *discard(2) is fine.
Examples #add two matrices X = [[12, 7, 3], [4 , 5, 6], [7 , 8, 9]] Y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]] result = [[0, 0, 0], [0, 0, 0]] #iterate through rows for i in range(len(X)): #iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j]+Y[i][j] for r in result: print(r)
Examples # Program to sort alphabetically the words form a string provided by the user # change this value for a different result my_str = "Hello this Is an Example With cased letters" # uncomment to take input from the user The sorted words are: #my_str = input("Enter a string: ") Example # breakdown the string into a list of words Hello Is words = my_str. split() With # sort the list an words. sort() cased print("The sorted words are: ") letters for word in words: this print(word)
- Slides: 26