Presentation is loading. Please wait.

Presentation is loading. Please wait.

Presented by Mirza Elahi 10/29/2018

Similar presentations


Presentation on theme: "Presented by Mirza Elahi 10/29/2018"— Presentation transcript:

1 Presented by Mirza Elahi 10/29/2018
PYTHON DATATYPES CPS 6195 Presented by Mirza Elahi 10/29/2018

2 Outline Python Datatypes Numbers List Tuple String Set Dictionary
Nested Dictionary Arrays Matrix List Comprehension

3 Number Data Type 3 different class, int, float, complex Functions,
>>>5 int(-5.3) >>>-5 float(2) >>>2.0 complex(‘7+11j’) >>>(7+11j) print( ) >>>3.0 Functions, type(), isinstance() a = 1 b = 2.0 c = j print(type(a)) print(type(b)) print(type(c)) print(isinstance(c, complex))

4 Number System Decimal, base 10 Binary, base 2 Hexadecimal, base 16
Octal, base 8 print(0b ) 107 print(0xFB + 0b10) 253 ( ) print(0o15) 13

5 Type Conversion Decimal (1.1 + 2.2) == 3.3 >>>False
print( ) >>> 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

6 Mathematics math import math print(math.pi) 3.141592653589793
print(math.cos(math.pi)) -1.0 Rand import random print(random.random()) print(random.randrange(1, 10)) x = ['a', 'b', 'c', 'd', 'e'] print(random.choice(x)) random.shuffle(x) print(x)

7 List List methods list.method() print(cps.count(2)) 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))

8 List Comprehension List comprehension Built in list functions
cps =[2 ** x for x in range(10)] 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 cps =[] For x in range(10): cps.append(2 ** x)

9 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))

10 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'))

11 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)

12 String String is sequence of characters.
Characters are encoded with 0’s and 1’s by the computer. Python uses Unicode. Create String cps = ‘Utep’ cps = “Utep” cps = ’’’Utep’’’ cps = “““Hello, welcome to the CPS program””” Indexing, Slicing cps = ‘cps2018' 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])

13 Operations cps = ‘Utep2018’ cps[-1] = ‘7’ cps = ‘Welcome’ del cps[1]
Elements of string cannot be changed but can be reassigned to the same name. cps = ‘Utep2018’ cps[-1] = ‘7’ cps = ‘Welcome’ del cps[1] del cps Membership Test using ‘in’ ‘u’ in ‘utep’ ‘t’ not in ‘utep’ Concatenation cps1 = ‘Utep’ cps2 = ‘2018’ print(‘cps1+cps2=’, cps1 + cps2) Print(‘cps1 * 3=’, cps1*3) Iteration count = 0 for letter in ‘utep cps': if(letter == ‘p'): count += 1 print(count,'letters found')

14 More Operations Built in functions cps = ‘utep'
list_enumerate = list(enumerate(cps)) print('list(enumerate(cps) = ', list_enumerate) print('len(cps) = ', len(cps))

15 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?\"")

16 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))

17 Change & Remove Elements
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("HelloWorld") print(cps.pop()) >>>W print(cps.clear()) >>>None

18 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}

19 Set Methods Set Membership Test cps = set(“Utep”) Print(‘U’ in cps)
>>>True Print(‘p’ not in cps) >>>False

20 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})

21 Q&A

22 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)

23 Quiz 2. Can you change the elements of a string? Yes or No. >>> cps = 'programiz’ >>> cps[5] = ‘a’ ... TypeError: '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] ... IndexError: string index out of range integer >>> cps[1.5] ... TypeError: string indices must be integers

24 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]} TypeError: 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.

25 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], [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)

26 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 #my_str = input("Enter a string: ") # breakdown the string into a list of words words = my_str.split() # sort the list words.sort() print("The sorted words are:") for word in words: print(word) The sorted words are: Example Hello Is With an cased letters this


Download ppt "Presented by Mirza Elahi 10/29/2018"

Similar presentations


Ads by Google