Revision Notes (PDF)
Document Details
Uploaded by EnviableDaisy
Tags
Summary
These notes cover revision topics on data structures and algorithms. The notes include questions and answers in Python. The document also covers various list operations, looping through lists, and range() functions.
Full Transcript
Introduction to “Revision” 1 Q1 Write a function Intersec(D1, D2) that takes two dictionaries D1 and D2, and returns a new dictionary with the common keys in D1 and D2. Example: D1 = {1:'a', 2:'b', 3:'c'} D2 = {2:'x', 4:'y', 1:'z'} Intersec(D1, D2) => {1: ['a...
Introduction to “Revision” 1 Q1 Write a function Intersec(D1, D2) that takes two dictionaries D1 and D2, and returns a new dictionary with the common keys in D1 and D2. Example: D1 = {1:'a', 2:'b', 3:'c'} D2 = {2:'x', 4:'y', 1:'z'} Intersec(D1, D2) => {1: ['a', 'z'], 2: ['b', 'x']} 2 Answer def Intersec(D1, D2): res = {} for i in D1: if i in D2: res[i] = [D1[i],D2[i]] return res D1 = {1:'a', 2:'b', 3:'c'} 3 D2 = {2:'x', 4:'y', 1:'z'} print( Intersec(D1, D2)) Q2 Write a function Round(n) that takes a float number n and returns n rounded to the nearest integer. Note: you are not allowed to use the round built-in function Example: Round (3.5) => 4 Round (2.2) => 2 4 Answer def Round(n): if n - int(n) >= 0.5: return int(n) + 1 return int(n) print (Round(3.5)) 5 Q3 Consider a text file where each line contains 3 integers separated by commas. For each line, the 1st integer is at position 0, the 2nd integer is at position 1, and the 3rd integer is at position 2. A column of data is defined as all integers in the file with the same position. Write a function ColAvg(F) that takes a file name F of the above format and returns a list of the averages of each column. Example: numbers.txt 3,2,6 2,3,3 1,10,15 6 ColAvg (“numbers.txt”) => [2, 5, 8] Q3 answer Answer: def ColAvg(F): fin = open(F,'r') res = [0,0,0] lines = fin.readlines() i=0 for line in lines: for num in line.split(','): res[i] += int(num) i += 1 i=0 for i in range(len(res)): res[i] = int(res[i]/len(lines)) return res 7 print (ColAvg("numbers.txt")) Q4 Write a function missing(L,n) that takes a list L and an integer n. The list contains numbers from 1 to n except a missing number. Your function should return this missing number. Example: missing([1,2,4,5], 5) => missing([1,2,3,4,5], 6) => missing([1,2,4],6) =>[3,5,6] 8 Q4 answer def missing(L, n): set1=set(L) L2=list(range(1,n+1)) set2=set(L2) diff=list(set2-set1) return diff print(missing([1,2,4,5], 5)) 9 Q5 Write a function CountInList(L) that takes a list L to count the number of zeros, even and odd numbers from a List of numbers Example: CountInList([0,33,25,64,58,0,66,94,23,47,45,0,29,28 ]) Output : Number of Zeros: 3 Number of evens: 5 Number of odds: 6 10 Q5 answer def CountInList(L): count_zeros=0 count_odd=0 count_even=0 for i in L: if i==0: count_zeros+=1 elif i%2==0: count_even+=1 else: count_odd+=1 return count_zeros,count_even,count_odd zeros,evens,odds=CountInList([0,33,25,64,58,0,66,94,23,47,45,0,29,28]) print("Number of Zeros: ",zeros) 11 print("Number of evens: ",evens) print("Number of odds: ",odds) Write the output of the following programs x = [1, 2, 3] for item in x: item = item + 1 print (x) [1, 2, 3] 12 Write the output of the following programs x = [[1, 2], [], [8, 9, 3]] for i in range(len(x)): x[i].append(5) print(x) [[1, 2, 5], , [8, 9, 3, 5]] 13 Write the output of the following programs D={' Tunisia':[1,3,5,0], 'Egypt':[2,4,6,4]} for i in D.values(): S=0 for x in i: S+=x print (S/len(i)) 2.25 14 4.0 Write the output of the following programs ph = 3 if ph < 7: print (“It’s acidic”) elif ph < 4: print (“It’s a strong acid”) It's acidic 15 Write the output of the following programs x = 1256 i = 10 while i < = 1000: print (x // i) i = i * 10 125 12 16 1 Write the output of the following programs Points=(3,4) Points=5 Print(points) It will give you an error as tuples are 17 immutable Introduction to “Revision” 1 Q1 Write a function Intersec(D1, D2) that takes two dictionaries D1 and D2, and returns a new dictionary with the common keys in D1 and D2. Example: D1 = {1:'a', 2:'b', 3:'c'} D2 = {2:'x', 4:'y', 1:'z'} Intersec(D1, D2) => {1: ['a', 'z'], 2: ['b', 'x']} 2 Answer def Intersec(D1, D2): res = {} for i in D1: if i in D2: res[i] = [D1[i],D2[i]] return res D1 = {1:'a', 2:'b', 3:'c'} 3 D2 = {2:'x', 4:'y', 1:'z'} print( Intersec(D1, D2)) Q2 Write a function Round(n) that takes a float number n and returns n rounded to the nearest integer. Note: you are not allowed to use the round built-in function Example: Round (3.5) => 4 Round (2.2) => 2 4 Answer def Round(n): if n - int(n) >= 0.5: return int(n) + 1 return int(n) print (Round(3.5)) 5 Q3 Consider a text file where each line contains 3 integers separated by commas. For each line, the 1st integer is at position 0, the 2nd integer is at position 1, and the 3rd integer is at position 2. A column of data is defined as all integers in the file with the same position. Write a function ColAvg(F) that takes a file name F of the above format and returns a list of the averages of each column. Example: numbers.txt 3,2,6 2,3,3 1,10,15 6 ColAvg (“numbers.txt”) => [2, 5, 8] Q3 answer Answer: def ColAvg(F): fin = open(F,'r') res = [0,0,0] lines = fin.readlines() i=0 for line in lines: for num in line.split(','): res[i] += int(num) i += 1 i=0 for i in range(len(res)): res[i] = int(res[i]/len(lines)) return res 7 print (ColAvg("numbers.txt")) Q4 Write a function missing(L,n) that takes a list L and an integer n. The list contains numbers from 1 to n except a missing number. Your function should return this missing number. Example: missing([1,2,4,5], 5) => missing([1,2,3,4,5], 6) => missing([1,2,4],6) =>[3,5,6] 8 Q4 answer def missing(L, n): set1=set(L) L2=list(range(1,n+1)) set2=set(L2) diff=list(set2-set1) return diff print(missing([1,2,4,5], 5)) 9 Q5 Write a function CountInList(L) that takes a list L to count the number of zeros, even and odd numbers from a List of numbers Example: CountInList([0,33,25,64,58,0,66,94,23,47,45,0,29,28 ]) Output : Number of Zeros: 3 Number of evens: 5 Number of odds: 6 10 Q5 answer def CountInList(L): count_zeros=0 count_odd=0 count_even=0 for i in L: if i==0: count_zeros+=1 elif i%2==0: count_even+=1 else: count_odd+=1 return count_zeros,count_even,count_odd zeros,evens,odds=CountInList([0,33,25,64,58,0,66,94,23,47,45,0,29,28]) print("Number of Zeros: ",zeros) 11 print("Number of evens: ",evens) print("Number of odds: ",odds) Write the output of the following programs x = [1, 2, 3] for item in x: item = item + 1 print (x) [1, 2, 3] 12 Write the output of the following programs x = [[1, 2], [], [8, 9, 3]] for i in range(len(x)): x[i].append(5) print(x) [[1, 2, 5], , [8, 9, 3, 5]] 13 Write the output of the following programs D={' Tunisia':[1,3,5,0], 'Egypt':[2,4,6,4]} for i in D.values(): S=0 for x in i: S+=x print (S/len(i)) 2.25 14 4.0 Write the output of the following programs ph = 3 if ph < 7: print (“It’s acidic”) elif ph < 4: print (“It’s a strong acid”) It's acidic 15 Write the output of the following programs x = 1256 i = 10 while i < = 1000: print (x // i) i = i * 10 125 12 16 1 Write the output of the following programs Points=(3,4) Points=5 Print(points) It will give you an error as tuples are 17 immutable Introduction to Non-Sequential Data Collections 1 Outline Lists Tuples Dictionary Set Operations of all … Adding and Deleting Elements Operators and Sets Looping and Sets 2 languages = ['English', 'Hindi', 'Chinese', 'Spanish', 'Bengali’] 3 LISTS Number list You can create a series of numbers using range() function. num = list(range(1, 11)) print(num) # output # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 4 Looping through lists programmingLanguages = ['python', 'java’, ‘c'] for pl in programmingLanguages: print("I know how to code in " + pl.title() + " programming language.") # output # I know how to code in Python programming language. # I know how to code in Java programming language. # I know how to code in C programming language. 5 range() function with for loop for i in range(1,11) : # output print(i) #1 #2 #3 #4 #5 #6 #7 #8 6 #9 # 10 Recap List operations num = list(range(1,11)) # output print(num) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(min(num)) # 1 print(max(num)) # 10 print(sum(num)) # 55 7 List comprehension List comprehension is an advanced approach to generating lists. List comprehension allows you to combine for loop to create a list. # without list comprehension cubes = [] for i in range(1,11): cube = i ** 3 cubes.append(cube) print(cubes) # with list comprehension cubes = [c ** 3 for c in range(1,11)] print(cubes) 8 # output # [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] Slicing List languages = ['English', 'Hindi', 'Chinese', 'Spanish', 'Bengali', 'Russian', 'Arabic', 'Portuguese'] # print list containing – english to bengali 0 'English’ print(languages[0:5]) 1 'Hindi’ # ['English', 'Hindi', 'Chinese', 'Spanish', 2 'Chinese’ 'Bengali'] # print list contains bengali, russian and 3 'Spanish’ arabic print(languages[4:7]) 4 'Bengali’ # ['Bengali', 'Russian', 'Arabic'] 5 'Russian’ # python by default start from the beginning. 6 'Arabic’ print(languages[:3]) 7 'Portuguese # ['English', 'Hindi', 'Chinese'] # similarly index for last element is the end default 9 print(languages[4:]) # ['Bengali', 'Russian', 'Arabic', 'Portuguese'] Copying a List languages = ['English', 'Hindi', 'Chinese', 'Spanish', 'Bengali', 'Russian', 'Arabic', 'Portuguese'] copy_languages = languages [ : ] print(languages) print(copy_languages) 10 Copying a List languages = ['English', 'Hindi', 'Chinese', 'Spanish', 'Bengali', 'Russian', 'Arabic', 'Portuguese'] copy_languages = languages print(languages) print(copy_languages) 11 languages = ('English', 'Hindi', 'Chinese', 'Spanish', 'Bengali') 12 TUPLES Tuples Like lists, tuples are collection types in python. Tuple use parentheses “(“ ,“)”. dimensions = (100, 20) output print(dimensions) 100 print(dimensions) 20 Tuples are immutable, which means the value of immutable lists cannot change. 13 Tuples are like lists Tuples are another kind of sequence that function much like a list - they have elements which are indexed starting at 0 >>> x = ['Glenn', 'Sally', 'Joseph’] >>> print (x) Joseph >>> x = ('Glenn', 'Sally', 'Joseph') >>> y = [1, 9, 2 ] >>> print >>> print (y) (x) Joseph [1, 9, 2] = ( 1, 9, 2 ) >>> y max(y) >>> print 9 >>> print (y) >>> for iter in y: (1, 9, 2) print (iter) >>> print max(y) 1 9 9 14 2..but.. Tuples are "immutable" Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string >>> x = [9, 8, 7] >>> x = 6 >>> print (x) [9, 8, 6] >>> y = 'ABC’ >>> y = ‘D’ Traceback: 'str' object does not support item Assignment >>> z = (5, 4, 3) 15 >>> z = 0 Traceback: 'tuple' object does not support item Assignment Modify tuple As tuple is immutable but we can overwrite tuple, we can completely change tuple values. dimensions = (100, 20) # output print(dimensions) # (100, 20) # assign new values to tuple dimensions = (500, 100) print(dimensions) # (500, 100) 16 unpack a tuple We can unpack a tuple by assigning it to a comma-separated list of variables dimensions = (100, 20) X_axis , Y_axis = output dimensions print(X_axis) 100 print(Y_axis) 20 17 Looping trough all tuple values we can loop through tuples as we did with a list. dimensions = (100, 20) # output # 100 for dimension in dimensions: # 20 print(dimension) They are mostly used when programmers want to store some value that can not be changed throughout the program. 18 Things not to do with tuples >>> x = (3, 2, 1) >>> x.sort() Traceback:AttributeError: 'tuple' object has no attribute 'sort’ >>> x.append(5) Traceback:AttributeError: 'tuple' object has no attribute 'append’ >>> x.reverse() Traceback:AttributeError: 'tuple' object has no attribute 'reverse’ 19 A Tale of Two Sequences >>> l = list() >>> dir(l) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> t = tuple() >>> dir(t) ['count', 'index'] 20 Tuples are more efficient they are simpler and more efficient in terms of memory use and performance than lists So in our program when we are making "temporary variables" we prefer tuples over lists. We can also put a tuple on the left hand side of an assignment statement >>> (x, y) = (4, 'fred’) >>> print (y) fred >>> (a, b) = (99, 98) 21 >>> print (a) 99 Tuples are Comparable The comparison operators work with tuples and other sequences If the first item is equal, Python goes on to the next element, and so on, until it finds elements that differ. >>> (0, 1, 2) < (5, 1, 2) True >>> (0, 1, 2000000) < (0, 3, 4) True >>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam’) True >>> ( 'Jones', 'Sally') > ('Adams', 'Sam’) 22 True Try it by yourself def calculator(X,Y): W=X+Y Z=X*Y return W,Z X=3 Y=4 res=calculator(X,Y) print(res) 23 print(type(res)) Question We have the following : >>> t = ([1,2,3], 'Hello') This tuple containing a list. What should we do to change the list to [4,5] 24 languages = {'eg':'English', 'hi':'Hindi', 'ch':'Chinese', ‘sp':'Spanish'} DICTIONARIES 25 Dictionaries Dictionaries are a collection of key and value pairs. each key is associated/connected with values. To access any value, we have to use the key, which is associated with value. We can use any data object as key or value myInformation = { 'name': 'Durgesh', 'age': 28 } # output print(myInformation['name']) Durges 26 h print(myInformation['age']) 28 What is a Dictionary? A Dictionary is an unordered, mutable collection of key-value pairs Example: Codes = {‘Mobinil’: ‘012’, ‘Vodafone’: ‘010’} >> Codes[‘Mobinil’] 012 Note the [ ] >> Codes[‘Vodafone’] 010 >> Codes[‘Etisalat’] KeyError: ‘Etisalat’ >> print Codes unordered 27 {‘Vodafone’: ‘010’, ‘Mobinil’: ‘012’} Note: A key can appear at most once in a dictionary (Unique) Tuples and Dictionaries The items() method in dictionaries returns a list of (key, value) tuples >>> d = dict() >>> d[‘id'] = 1002 >>> d[‘name'] = ‘Ali’ >>> for (k,v) in d.items(): print (k, v) id 1002 name Ali >>> tups = d.items() >>> print (tups) 28 [(‘id’, 1002), (‘name’, ‘Ali’)] Adding and Deleting Items To add an item to a Dictionary, assign a value to a key >> Codes[‘Etisalat’] = ‘011’ >> print Codes {‘Vodafone’: ‘010’, ‘Etisalat’: ‘011’, ‘Mobinil’: ‘012’} Note: if the key already exists its value is replaced To delete an Item from a Dictionary use del >> del Codes[‘Vodafone’] >> print Codes {‘Etisalat’: ‘011’, ‘Mobinil’: ‘012’} 29 Modifying Dictionary personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28 } print(personal) # output # {'fname': 'Durgesh', 'lname': 'Samariya', 'age': 28} # change fname and lname personal['fname'] = 'Hello' personal['lname'] = 'World' # output # {'fname': 'Hello', 'lname': 'World', 'age': 28} # add city as key and Melbourne as value personal['city'] = 'Melbourne' # output 30 # {'fname': 'Hello', 'lname': 'World', 'age': 28, 'city': 'Melbourne'} Removing key-value from Dictionary personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28, 'city':'Melbourne'} print(personal) # output # {'fname': 'Durgesh', 'lname': 'Samariya', 'age': 28, 'city':'Melbourne'} # remove city information del personal['city'] # output 31 # {'fname': 'Durgesh', 'lname': 'Samariya', 'age': 28} Looping in Dictionaries personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28, 'city':'Melbourne'} for p in personal : # output print(personal[p]) # Durgesh # Samariya # 28 # Melbourne If you use a Dictionary in a for statement, it traverses the keys of the dictionary 32 Dictionary Operations keys Returns the dictionary’s keys as a list. Entries are guaranteed to be unique. >> print ( list( Codes.keys() )) ['Mobinil', 'Etisalat', 'Vodafone'] values Returns the dictionary’s values as a list. Entries may or may not be unique. >> print ( list( Codes.values() )) ['012', '011', '010'] 33 Ex. personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28 } # output for key in personal.keys(): # fname print(key) # lname # age # output # Durgesh for value in personal.values(): # Samariya print(value) # 28 34 Dictionary Operations items Returns a list of (key, value) pairs. >> print ( list( Codes.items() )) [('Mobinil', '012'), ('Etisalat', '011'), ('Vodafone', '010')] get Returns the value associated with a key. >> print ( Codes.get( ‘Mobinil’ )) ‘012’ 35 Ex 1 personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28 } # output for key, value in personal.items(): # fname print(key) # Durgesh print(value) # lname # Samariya # age # 28 # Durgesh print (personal.get('fname’)) # Samariya 36 print (personal.get(‘lname’)) # 28 print (personal.get(‘age’)) Dictionary Operations clear Empties the dictionary. >> Codes.clear() update Updates the dictionary with the contents of another. Codes2 = {'Cairo':'02', 'Alex':'03'} Codes.update(Codes2) #output 37 {'Cairo': '02', 'Mobinil': '012', 'Alex': '03', 'Etisalat': '011', 'Vodafone': '010'} Example personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28 } person0 = { 'fname' : ‘Nouh', 'lname' : 'Sara', 'age’ : 20 } personal.update(person0) print(personal) 38 Example personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28 } person0 = { 'fname0' : 'Nouh', 'lname0' : 'Sara', 'age0' : 20 } personal.update(person0) print(personal) 39 Ex. personal = { 'fname' : 'Durgesh', 'lname' : 'Samariya', 'age' : 28 } person0 = { 'fname' : ‘Nouh', 'lname' : 'Sara', 'age’ : 20 } person0.clear() print(person0) # {} 40 Nested Dictionary you can store dictionaries in the list or vice versa. person1 = {'name':'Person1', 'age':28} person2 = {'name':'Person2', 'age':15} person3 = {'name':'Person3', 'age':40} persons = [person1, person2, person3] for person in persons: print(person) # output # {'name': 'Person1', 'age': 28} 41 # {'name': 'Person2', 'age': 15} # {'name': 'Person3', 'age': 40} create lists in dictionaries person = {'name':['Durgesh', 'Samariya'], 'age': 27} # output for key,value in person.items(): name print(key) ['Durgesh', 'Samariya'] print(value) age 27 Can you store a dictionary in the dictionary? 42 movies = { 'avatar': {'year': 2009, 'rating': 5}, 'inception’ : {'year': 2010, 'rating’: 5}, 'joker’ : {'year': 2019, 'rating': 4.5}, } print(movies['avatar']) # output # {'year': 2009, 'rating': 5} print(movies['avatar']['year']) 43 # output # 2009 languages = set(['English', 'Hindi', 'Chinese', 'Spanish']) SETS 44 What is a Set? A set is an unordered collection of distinct items >>> s = set([1, 2, 3, 4, 1, 2]) >>> print (s) duplicates removed {1, 2, 3, 4} >>> L = ['a','b','D','d','a'] >>> s = set (L) >>> print (s) ‘d’ ≠ ‘D’ {'a', 'b', 'D', 'd’} >>>s = set() # empty set 45 >>> print(s) {} Adding and Deleting Elements To add an element to a set use add() Example: >>> s.add(12) => s = {1,2,3,4,12} To delete an element from a set use remove() Example: >>> s.remove(3) => s = {1,2,4,12} To delete all elements from a set use clear() Example: >>> s.clear() 46 Returns None Set Operations Div2 = set ([2,4,6]) Div3 = set ([3,6,9]) union Creates a set with elements that are in either set >>> Div2.union(Div3) => {2, 3, 4, 6, 9} intersection Creates a set with elements that are in both sets >>> Div2.intersection(Div3) => {6} 47 Set Operations Div2 = set ([2,4,6]) Div3 = set ([3,6,9]) difference Creates a set with elements from one set, but not the other >>> Div2.difference(Div3) => {2, 4} symmetric_difference Creates a set with elements that are in exactly one set >>> Div2.symmetric_difference(Div3) {9, 2, 3, 4} 48 Set Operations S1 = set([2,4]) S2 = set([1,2,3,4]) issubset Asks are all of one set’s elements contained in another? >>> S1.issubset(S2) => True issuperset Asks does one set contain all of another’s elements? >>> S1.issuperset(S2) => False 49 Operators and Sets 50 Looping and Sets If you use a Set in a for statement, it traverses the elements of the set Example: s = set([1,2,3,4]) for e in s: print (e) Result: 1 2 3 51 4 in Operator To check membership of an element. >print ( '#' in 'Hi#’) True >print ( 3 in [4,5,6]) False >print (7 in {6: 'Ahmed’, 7: 'Belal’}) True >if 9 in {8,6}: 52 ? PROBLEMS 53 What does this code do??? 54 55 Resolve Q1 in Sheet 6 Write a program that takes two lists and prints a list containing the common elements between the two lists. 56 Summary Strings “..” indexed immutable Lists [..] indexed mutable Tuples (..) indexed immutable Dictionaries {..} unordered mutable Sets set( [ list] ) unordered mutable 57 Introduction to “File Processing” 1 Outline Introduction Opening a file Reading from a file Writing to a file Closing a file Reading from the Web 2 Introduction File Processing: is the process of reading or writing to a file and manipulating its data. File processing operations include: Opening a file Reading from a file Writing to a file Closing the file 3 Opening a File Before we can read the contents of the file we must tell Python which file we are going to work with and what we will be doing with the file This is done using the open() function open() returns a “file handle” - a variable used to perform operations on the file Kind of like “File -> Open” in a Word Processor 4 What is a Handle? >>> fhand = open('mbox.txt') >>> print (fhand) 5 Opening a file To open a file we use function open(, ) Name is a string with the actual file name on the disk. Open mode can be Read “r” Write “w” Append “a” depending on whether we are reading, writing or appending in the file. Example: >>> f = open ("C:\\file1.txt",'r') >>> print f >> type (f) 0x00000000021BEA50 > Opening a file To open a file we use function open(, ) Name is a string with the actual file name on the disk. Open mode can be Read “r” Write “w” Append “a” depending on whether we are reading, writing or appending in the file. Unless the file already exists, Example: you will get an error: >>> fi = open ("C:\\file1.txt",'r') >>> print fi >> type (fi) 0x00000000021BEA50 > Opening a file To open a file we use function open(, ) Name is a string with the actual file name on the disk. Open mode can be Read “r” Write “w” Append “a” depending on whether we are reading, writing or appending in the file. Example: >>> fo = open ("C:\\file2.txt",’w') >>> print fo if the file does not exist, it will be created; 8 >>> type (fo) If the file already exists, it will overwrite its contents Opening a file To open a file we use function open(, ) Name is a string with the actual file name on the disk. Open mode can be Read “r” Write “w” Append “a” depending on whether we are reading, writing or appending in the file. Example: >>> fo = open ("C:\\file2.txt",’a') >>> print fo if the file does not exist, it will be created; >>> type (fo) If the file already exists, it will point at the beginning of its 9 contents waiting for your commands (read or write). If you want to add then you need to move to its end to add content. Reading from a file How to read data from the file ? There are 3 different methods to read data from files readline () returns the next line in the file as a string. readlines () returns all lines in the file as a list of strings (lines) read() returns the entire file content as one string. Example: >>> fin = open ( 'file1.txt' , 'r' ) If the file is empty, readline() and >>> Line = fin.readline() readlines() will return an emty string and empty list. >>> Lines = fin.readlines() 10 file1.txt Assume the following contents in file1.txt 11 The newline Character We use a special character to indicate >>> stuff = 'X\nY’ when a line ends >>> print (stuff) X called the "newline" Y We represent it as \n >>> len (stuff) in strings 3 Newline is still one character - not two 12 A closer look at reading lines Removes any white spaces at the beginning or end of the string. 13 A closer look at reading lines Removes any white spaces at the beginning or end of the string. Notice how reading resumed from the last point, rather than restarting form the beginning of the file 14 Reading from a file (cont.) read() : reads the entire contents of the file content as a string including “newline” characters “\n”. 15 Reading from a file (cont.) Seek (offset) method: sets the file's current position at the offset (character position). Will start reading a line from the 4th character in the file. will go back to the beginning of the file! Will start reading a line from the 21th character in the file. 16 Looping over the contents of a file 17 Searching Through a File We can put an if statement in our for loop to only print fhand = open('mbox-short.txt') lines that meet for line in fhand: some criteria if line.startswith('From:') : print (line) 18 Searching Through a File (fixed) fhand = open('mbox-short.txt') We can strip the for line in fhand: whitespace from the line = line.rstrip() if line.startswith('From:') : right hand side of the print (line) string using rstrip() from the string library The newline is From: [email protected] considered "white From: [email protected] space" and is stripped From: [email protected] From: [email protected].... 19 Using in to select lines We can look for a fhand = open('mbox-short.txt') string anywhere in a for line in fhand: line as our selection line = line.rstrip() criteria if '@uct.ac.za' in line : print (line) From [email protected] Sat Jan 5 09:14:16 2008 X-Authentication-Warning: set sender to [email protected] using –f From: [email protected]: [email protected] From [email protected] Fri Jan 4 07:02:32 2008 X-Authentication-Warning: set sender to [email protected] using -f... 20 Prompt for fname = input('Enter the file name: ') fhand = open(fname) count = 0 for line in fhand: if line.startswith('Subject:') : File Name count = count + 1 print ('There were', count, 'subject lines in', fname) Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt Enter the file name: mbox-short.txt There were 27 subject lines in mbox-short.txt 21 Closing files Whether you are reading or writing you always need to close a file after you’re done processing it. In some cases, not properly closing a file could result in data loss. To close a file , use the close( ) method Example: >>> f.close() 22 Writing to a file To write to a file , use “w” open mode What will happen to the file in “w” mode ?? File exists: clear the file’s contents. File doesn’t exists: a new one is created. Example: >>> f =open ("file2.txt",'w') >>> f.write ("Hello") >>> f.close() When you are done writing, you have to close the file to see the updates 23 Writing to a file (Cont.) What if you want to write data to your file? Lets take the example of wanting to write numbers! Example: >>> f =open ("file2.txt",'w') >>> f.write (7) TypeError: expected a character buffer object Use the string formatting operators % Example: >>> f =open ("file2.txt",'w') >>> n= 7 >>> f.write ("this is number %d" %(n)) 24 Writing to a file (Cont.) To append the file content without deleting the original content, use “a” open mode Example: >>> f =open ("file2.txt",'a') “Hi” will be added to the file >>> f.write ("Hi") content without deleting the previous data. >>> f.close() To write a new line in the file, use “ \n” Example: >>> f =open ("file2.txt",'a') >>> f.write ("\n Welcome") “Welcome” will be added in a >>> f.close() new line. 25 The flush method Data is usually buffered in memory before its actually written to a file. You will notice that you will only see what you have written to file after closing it. If you want to force the contents of the buffer to be written to the file, you can use the flush method. Example: f =open ("file2.txt",‘w') Open the file now. You’ll see that its empty f.write(“hello") f.flush() Now, re-open the file. You’ll see ‘hello’ has been written 26 Reading from URLs!! import urllib url = "http://www.nileu.edu.eg/" web_page = urllib.urlopen(url) for line in web_page: line = line.strip() print line web_page.close() 27 Introduction to “Functions” 1 Outline Functions WRITE and CALL/INVOKE A FUNCTION FUNCTION BODY VARIABLE SCOPE Return Vs. Print FUNCTIONS AS ARGUMENTS 2 What are functions? write reusable pieces/chunks of code, called functions. functions are not run in a program until they are “called” or “invoked” in a program. function characteristics: has a name. has parameters (0 or more). has a docstring (optional but recommended). has a body. 3 returns something. Python Functions There are two kinds of functions in Python. Built-in functions that are provided as part of Python - input(), type(), float(), int()... Functions that we define ourselves and then use NOTE: Try to treat the built-in function names as "new" reserved words (i.e. we avoid them as variable names) Python will allow to reuse them HOWEVER not recommended. Building our Own Functions We create a new function using the def keyword followed by optional parameters in parenthesis. We indent the body of the function This defines the function but does not execute the body of the function def print_lyrics(): print ("I'm a lumberjack, and I'm okay.”) print ('I sleep all night and I work all day.‘) Question? What is the difference between: Built-In Functions Type conversion (int, float) I/O (print, input) Imported Functions Math functions (sin, sqrt) User Defined Functions def ………… Reserved words if, while, for, try, except, def, import 6 print ("I'm a lumberjack, and I'm okay.“) print_lyrics(): x=5 print ('I sleep all night and I work all day.‘) print ('Hello‘) def print_lyrics(): print ("I'm a lumberjack, and I'm okay.”) print ('I sleep all night and I work all day.‘) Hello Yo print ('Yo‘) 7 x=x+2 print (x) x=5 print ('Hello‘) def print_lyrics(): print ( "I'm a lumberjack, and I'm okay.” ) print ( 'I sleep all night and I work all day.') print ( 'Yo') print_lyrics() Hello x=x+2 Yo print ( x) I'm a lumberjack, and I'm okay.I sleep all night and I work all day. 7 Definitions and Uses Once we have defined a function, we can call (or invoke) it as many times as we like This is the store and reuse pattern Stored (and reused) Steps def hello(): Program: print 'Hello' Output: def hello(): print 'Fun' print ('Hello’) print ('Fun’) Hello hello() Fun hello() print ('Zip’) Zip print “Zip” hello() Hello Fun hello() We call these reusable pieces of code “functions”. HOW TO WRITE and CALL/INVOKE A FUNCTION 11 IN THE FUNCTION BODY 12 VARIABLE SCOPE formal parameter gets bound to the value of actual parameter when function is called. new scope/frame/environment created when enter a function. scope is mapping of names to objects. 13 ONE WARNING IF NO return STATEMENT Python returns the value None, if no return given. 14 Represents the absence of a value. Void (non-fruitful) Functions When a function does not return a value, we call it a "void" function Functions that return values are "fruitful" functions Void functions are "not fruitful" Return Vs. Print return only has print can be used in meaning inside a and outside function. functions. only one return can execute many executed inside a print statements function. inside a function. code inside function code inside function but after return can be executed after statement not a print statement executed. has a value has a value associated associated with it, 16 with it, given to outputted to the function caller. console FUNCTIONS AS ARGUMENTS arguments can take on any type, even functions. 17 SCOPE EXAMPLE inside a function, can access a variable defined outside. inside a function, cannot modify a variable defined outside -- can using global variables, but frowned upon. 18 SCOPE EXAMPLE inside a function, can access a variable defined outside. inside a function, cannot modify a variable defined outside -- can using global variables, but frowned upon. 19 Built-in functions Argument big = max( [3,6,23,9,11,0] ) Assignment 23 Result >>> big = max([3,5,23,9,11,0]) >>> print (big) 23 >>> tiny = min([3,5,23,9,11,0]) >>> print (tiny) 0 Max Function A function is some stored code that we >>> big = max([3,5,23,9,11,0]) use. >>> print (big) A function takes some 23 input and produces an output. [3,5,23,9,11,0] max() 23 function (type int) (type list) Guido wrote this code Max Function A function is some stored code that we >>> big = max([3,5,23,9,11,0]) use. >>> print (big) A function takes some 23 input and produces an output. def max(inp): blah [3,5,23,9,11,0] max() blah 23 for x in y: function (type int) (type list) blah blah Guido wrote this code Type Conversions >>> print (float(99) / 100) 0.99 >>> i = 42 >>> type(i) When you put an integer and >>> f = float(i) floating point in an expression the integer is implicitly >>> print (f) converted to a float 42.0 >>> type(f) You can control this with the built in functions int() and float() >>> print (1 + 2 * float(3) / 4 – 5) -2.5 >>> String >>> sval = '123' >>> type(sval) Conversions >>> print (sval + 1) You can also use int() Traceback (most recent call last): File "", line 1, in and float() to convert TypeError: cannot concatenate 'str' and 'int' between strings and >>> ival = int(sval) integers >>> type(ival) You will get an error if >>> print (ival + 1) 124 the string does not >>> nsv = 'hello bob' contain numeric >>> niv = int(nsv) characters Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() String >>> sval = '123' >>> type(sval) Conversions >>> print (sval + 1) You can also use int() Traceback (most recent call last): File "", line 1, in and float() to convert TypeError: cannot concatenate 'str' and 'int' between strings and >>> ival = int(sval) integers >>> type(ival) You will get an error if >>> print (ival + 1) 124 the string does not >>> nsv = 'hello bob' contain numeric >>> niv = int(nsv) characters Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() String >>> nsv = 'hello bob' >>> niv = int(nsv) Conversions Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() You can also use int() >>> sval = '123' >>> type(sval) and float() to convert between strings and >>> print (sval + 1) integers Traceback (most recent call last): File "", line 1, in You will get an error if TypeError: cannot concatenate 'str' and 'int' the string does not >>> while = int(sval) contain numeric >>> type(ival) characters >>> print (ival + 1) 124 >>> def greet(lang): Parameters...... if lang == 'es': print ('Hola’)... elif lang == 'fr':... print ('Bonjour’) A parameter is a variable... else: which we use in the... print ('Hello’) function definition that is a... “handle” that allows the >>> greet('en') code in the function to Hello access the arguments for a >>> greet('es') particular function Hola invocation. >>> greet('fr') Bonjour >>> >>> def greet(lang): Return Value...... if lang == 'es': return 'Hola’... elif lang == 'fr':... return 'Bonjour’ A “fruitful” function is one... else: that produces a result (or... return 'Hello’ return value)... >>> print (greet('en'),'Glenn’ ) Hello Glenn The return statement ends >>> print (greet('es'),'Sally’ ) the function execution and Hola Sally “sends back” the result of >>> print (greet('fr'),'Michael’ ) the function Bonjour Michael >>> Arguments, Parameters, and Results >>> big = max( [3,6,23,9,11,0] ) Parameter >>> print (big) 23 def max(inp): blah [3,6,23,9,11,0] blah 23 for x in inp: Argument blah Result blah return 23 Multiple Parameters / Arguments We can define more than one parameter in the function definition def addtwo(a, b): We simply add more added = a + b arguments when we call the return added function x = addtwo(3, 5) print (x) We match the number and order of arguments and parameters To function or not to function... Organize your code into “paragraphs” - capture a complete thought and “name it” Don’t repeat yourself - make it work once and then reuse it If something gets too long or complex, break up logical chunks and put those chunks in functions Make a library of common stuff that you do over and over - perhaps share this with your friends... Summary Functions Built-In Functions Type conversion (int, float) I/O (print, input) Imported Functions Math functions (sin, sqrt) User Defined Functions def ………… Try / except (again) Arguments Parameters Introduction to “Computing with Strings” Outline What is a String? String Operations Concatenation Repetition Indexing Length Slicing String Printing Escape characters Multiline string Formatted printing Outline - cont String Input Casting Evaluating Strings String Representation – (Ord and chr) The String Library Why Strings? Many programs depend on string usage and manipulation An example problem: Write a program to emulate an intelligent ChatBot… To solve a problem like that, you need to learn about strings What is a String? A string is a sequence of characters Strings are delimited by single ‘ ‘ or double “ “ quotes Strings can be stored in variables Example: >>> Str1 = “hello” >>> Name = ‘Ahmed’ >>> ‘that’ll not work’ SyntaxError: invalid syntax >>> “that’ll work” What if you want to put both kinds of quote in one string? Strings think of as a sequence of case sensitive characters can compare strings with ==, >, < etc. len() is a function used to retrieve the length of the string in the parentheses s = "abc" len(s) evaluates to 3 6 Strings square brackets used to perform indexing into a string to get the value at a certain index/position s = "abc" index: 0 1 2 indexing always starts at 0 index: -3 -2 -1 last element always at index -1 s evaluates to "a" s evaluates to "b" s evaluates to "c" s trying to index out of bounds, error s[-1] evaluates to "c" 7 s[-2] evaluates to "b" s[-3] evaluates to "a" String Operations: Indexing Indexing is used to access the individual characters that make up the string Characters in a string are indexed from 0 to the length of the string - 1 Example: >>> greet = ‘Hello Bob’ >>>greet ‘e’ >>>greet IndexError: string index out of range Note: Strings are immutable i.e. you can not edit a string Example: >>> greet = ‘p’ TypeError: 'str' object does not support item assignment String Operations: 1. Concatenation The + operator can be used to join 2 strings Note the space Example: here >>> print (‘hello ’ + “world”) hello world >>> print (‘1’ + ‘2’) 12 >>> Fname = ‘Foo’ >>> print (‘Welcome ’ + Fname) Welcome Foo Strings strings are “immutable” – cannot be modified s = "hello" s = 'y' gives an error s = 'y'+s[1:len(s)] is allowed, s bound to new object 10 String Input Python provides input function called input() that does not evaluate the expression that the user types Example: >>> name = input() Ahmed >>> print (‘hello’, name) hello Ahmed >>> expression = input(“enter an expression: “) enter an expression: 3 + 2 - 1 >>> print( ‘x = ‘ + expression) x=3+2-1 Simple ChatBot Believe it or not! That’s all you need to know to solve the problem given at the beginning. Here is the code: print( "Hi There...") print( "What's your name?") name = input("My name is: ") print( "Nice to meet you " + name) print( "How are you feeling today?") feeling = input("I am feeling ") print( "Glad you are feeling " + feeling ) print( "It was nice meeting you " + name+ ". Hope you have a very nice day!") print( "Have fun in CSCE 201 today ;-) ") But there is still soooo much more String Operations: Repetition Repetition builds a string by multiple concatenations of a string with itself We can repeat a string using the * operator Example: >>> ‘hi’ * 3 ‘hihihi’ >>> ’12’ * 2 ‘1212’ String Operations: Length Python provides a built-in function called len that returns the number of characters in a string Example: >>> name = “Bob” >>> len (name) 3 >>> len (‘hello’) 5 To get the last letter of a string >>> x = len(name) >>> print( name[x-1]) Note the -1 ‘b’ String Operations: Slicing Slicing is used to access a substring from a string Slicing takes the form string [start : end] Including start and excluding end Example: -5 -4 -3 -2 -1 >>> country = ‘Egypt’ E g y p t >>> country [1:3] ‘gy’ 0 1 2 3 4 >>> country [2:] ‘ypt’ Note that the slice >>> country [:4] stops before the end ‘Egyp’ index >>> country [-3:4] ‘yp’ Strings can slice strings using [start:stop:step] if give two numbers, [start:stop], step=1 by default you can also omit numbers and leave just colons s = "abcdefgh" s[3:6] evaluates to "def", same as s[3:6:1] s[3:6:2] evaluates to "df" s[::] evaluates to "abcdefgh", same as s[0:len(s):1] s[::-1] evaluates to "hgfedcba", same as s[-1:- 17 (len(s)+1):-1] s[4:1:-2] evaluates to "ec" for LOOPS RECAP for loops have a loop variable that iterates over a set of values for var in range(4): var iterates over values 0,1,2,3 expressions inside loop executed with each value for var for var in range(4,6): var iterates over values 4,5 range is a way to iterate over numbers, but a for loop variable can iterate over any set of values, not just numbers! 18 STRINGS AND LOOPS these two code snippets do the same thing bottom one is more “pythonic” s = "abcdefgh" for index in range(len(s)): if s[index] == 'i' or s[index] == 'u’: print("There is an i or u") for char in s: if char == 'i' or char == 'u’: print("There is an i or u") 19 Exercise s1 = "mit u rock" s2 = "i rule mit" if len(s1) == len(s2): for char1 in s1: for char2 in s2: if char1 == char2: print("common letter”,char2) break String Printing 1. Escape Characters Escape characters are used inside a string to “escape” from Python’s usual syntax rules for a moment Example: >>> print( ‘she said, “that\’s hard to read”’) she said, ”that's hard to read” >>> print (“hello \n world”) hello world String Printing 3. Formatted Printing To print the value of a variable with a string we can use 1. Comma-separation >>> p = 3 >>> print (“price =“, p, “$”) Comma-separated strings price = 3 $ will be separated by a space 2. Concatenation >>> name = ‘Ahmed’ >>> print (‘welcome ’ + name) Concatenation can only be used between 2 strings welcome Ahmed >>> print (“price =“ + p + “$”) TypeError: cannot concatenate 'str' and 'int‘ String Printing %d Integer 3. Formatted Printing %f Float %s String 3. String formatting >>> p = 5 >>> t = 34.5 >>> c = ‘Egypt’ >>> print (“price = %d” %(p)) price = 5 >>> print (“temp in %s = %f degrees” %(c,t)) temp in Egypt = 34.500000 degreesIndicates precision >>> print (“temp in %s = %.1f degrees” %(c,t)) temp in Egypt = 34.5 degrees Indicates width >>> print (“temp in %s = %10.1f degrees” %(c,t)) temp in Egypt = 34.5 degrees Casting (Type Conversion) In Python you can convert a variable from a type to another To get the type of a variable use the type(var) function Example: >>> x = 3 >>> type(x) To convert x to a float use the float(var) function Example: >>> x = float(x) >>> type(x) float (expr) Convert expr to a floating point value >>> str (1 + 3) int (expr) Convert expr to an integer value ‘4' str (expr) Return a string representation of expr String Representation Python provides built-in functions to switch between characters and their numeric codes The ord() function returns the numeric “ordinal” code of a single-character string Example: >>> ord (“a”) 97 Note that ‘a’ ≠ ‘A’ >>> ord (“A”) 65 The chr() function is the opposite of ord() Example: A common usage of ord and chr is in >>> chr(97) Encryption ‘a’ Evaluating Strings Python provides a function eval(expr) used to evaluate a string as an expression Example: >>> eval (‘1 + 4 * 2’) 9 >>> eval (‘3.5 – 1‘) 2.5 Note that int() is used for conversion not evaluation >>> int (‘1+5’) ValueError: invalid literal for int() Evaluating Strings What if expression is not an expression Note that some characters are in Example: the eval expression >>> eval (‘1 + hi * 2’) NameError: name 'hi' is not defined TRY. EXCEPT 28 The try / except Structure You surround a dangerous section of code with try and except. If the code in the try works - the except is skipped If the code in the try fails - it jumps to the except section Will this code work properly? astr = 'Hello Bob’ istr = int(astr) print ('First', istr) astr = '123’ istr = int(astr) print ('Second', istr) astr = 'Hello Bob’ istr = int(astr) print 'First', istr The program stops here astr = '123’ ? istr = int(astr) print 'Second', istr All Done When the first astr = 'Hello Bob' conversion fails - it try: just drops into the istr = int(astr) except: clause and except: the program istr = -1 continues. Program Output print ('First', istr) First -1 astr = '123' Second 123 try: When the second istr = int(astr) conversion except: succeeds - it just istr = -1 skips the except: clause and the print ('Second', istr) program continues. try / except astr = 'Bob' astr = 'Bob' try: print 'Hello' print 'Hello' istr = int(astr) istr = int(astr) print ('There‘) print 'There' except: istr = -1 istr = -1 print 'Done', istr Safety net print ('Done', istr) Sample try / except rawstr = input('Enter a number:') try: ival = int(rawstr) Sample Run 1 except: Enter a number:42 ival = -1 Nice work if ival > 0 : Sample Run 2 print ('Nice work‘) Enter a number:fourtytwo else: Not a number print ('Not a number‘) Sample try / except Division by Zero x = int(input('Enter x>>')) y = int(input('Enter y>>')) Enter x>>1 try: Enter y>>0 z = x/y Handling run-time error: division by zero except ZeroDivisionError as err: print('Handling run-time error:', err) String Comparison if word == 'banana': print ( 'All right, bananas.‘) if word < 'banana': print ('Your word,' + word + ', comes before banana.’) elif word > 'banana': print ('Your word,' + word + ', comes after banana.’) else: print ('All right, bananas.‘) String Library Python has a number of string functions which are in the string >>> greet = 'Hello Bob‘ library >>> zap = greet.lower() These functions are already built into >>> print zap every string - we invoke them by hello bob appending the function to the string >>> print greet variable Hello Bob >>> print 'Hi There'.lower() These functions do not modify the hi there original string, instead they return a >>> new string that has been altered The String Methods >>> stuff = 'Hello world’ >>> type(stuff) >>> dir(stuff) ['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] http://docs.python.org/lib/string-methods.html http://docs.python.org/lib/string-methods.html String Library str.capitalize() str.replace(old, new[, count]) str.center(width[, fillchar]) str.lower() str.endswith(suffix[, start[, end]]) str.rstrip([chars]) str.find(sub[, start[, end]]) str.strip([chars]) str.lstrip([chars]) str.upper() http://docs.python.org/lib/string-methods.html Searching a String We use the find() function b a n a n a to search for a substring within another string 0 1 2 3 4 5 find() finds the first >>> fruit = 'banana' >>> pos = fruit.find('na') occurance of the substring >>> print pos If the substring is not found, 2 find() returns -1 >>> aa = fruit.find('z') >>> print aa Remember that string -1 position starts at zero Making everything UPPER CASE >>> greet = 'Hello Bob' You can make a copy of a string in >>> nnn = greet.upper() lower case or upper case >>> print nnn Often when we are searching for a HELLO BOB >>> www = greet.lower() string using find() - we first convert >>> print www the string to lower case so we can hello bob search a string regardless of case >>> Search and Replace The replace() function is like a >>> greet = 'Hello Bob' “search and replace” >>> nstr = greet.replace('Bob','Jane') operation in a word >>> print nstr processor Hello Jane It replaces all >>> nstr = greet.replace('o','X') >>> print nstrHellX BXb occurrences of the search string with the >>> replacement string Stripping Whitespace Sometimes we want to take a >>> greet = ' Hello Bob ' string and remove whitespace >>> greet.lstrip() at the beginning and/or end 'Hello Bob ' lstrip() and rstrip() to the left >>> greet.rstrip() ' Hello Bob' and right only >>> greet.strip() strip() Removes both begin 'Hello Bob' >>> and ending whitespace Prefixes >>> line = 'Please have a nice day’ >>> line.startswith('Please') True >>> line.startswith('p') False 21 31 From [email protected] Sat Jan 5 09:14:16 2008 >>> data = 'From [email protected] Sat Jan 5 09:14:16 2008’ >>> atpos = data.find('@') >>> print atpos 21 >>> sppos = data.find(' ',atpos) >>> print sppos 31 >>> host = data[atpos+1 : sppos] >>> print host Parsing and uct.ac.za Extracting Exercise s1 = ‘welcome to’ s2 = ‘CSCE’ s3 = ‘201’ Show the result of each of the following: 1. print (s1 + s2, s3) 2. print (s3*3) 3. print (int(s3)*3) 4. print (s1[2:5]) 5. print (s1.upper()) 6. print (s2.split(’s’)) 7. print (s1+’\\’+s2+’\t’+s3) Introduction to Revision by Examples 1 Example (1) Solving second degree equation ax2+bx+c using general law. 2 Example (2) Multiplication table. 3 Example (3) Factorial. 4 Example (4) Patterns. 5 Example (4) Patterns (another solution). 6 Example (7) Check Number is Divisible by 5 and 11 7 Example (8_1) Count Number of Digits in a Number using While Loop 8 Example (8_2) Sum Number of Digits in a Number using While Loop 9 Example (12) Reverse a Number Using 10 Example (9) Sum of Even and Odd Numbers from 1 to N using For Loop 11 Example (10) Prime 12 Example (10_2) print Prime Numbers from 1 to 100 using For Loop 13 Example (11) Fibonacci Series Fibonacci Series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 … 14 Example (5) Patterns (another solution). 15 Example (6) Patterns 16 Introduction to Loops and Lists 1 Outline The " for " loop Traversing a String Nested loops Breaking a loop What is a list? List Operations Concatenation Repetition Indexing Length Max, Min and Sum Slicing Aliasing List Methods Looping on lists 2 Control Structure 3 The order in which the programming statements are executed There are three main control flows: What are loops? In general, statements in a program are executed sequentially: the first statement in a function is executed first, followed by the second, and so on. But what if you encounter a situation, when a block of code needs to be executed several number of times? Example: what will you do if you are asked to print numbers between 0 and 100? Answer: Use loops 4 What are loops? – cont A loop statement allows us to execute a statement or group of statements multiple times. while :... evaluates to a Boolean 1. if is True, do all the steps inside the while code block 5 2. check again 3. repeat until is False The “while” Loop “while” loops are used for repeating sections of code as long as a condition is True Example: Initialization Output: count = 0 0 while count < 5: Condition 1 print (count) 2 Note count = count + 1 3 the 4 Indent Step 6 How many times will the code within the above loop run? 5 n=5 Repeated Steps No Yes Program: n>0? Output: print n n=5 5 while n > 0 : 4 print n 3 n = n -1 n=n–1 2 print ('Blastoff!‘) 1 print (n) Blastoff! print 'Blastoff' 0 Loops (repeated steps) have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers. Interactive Loops You can set the condition of a “while” loop based on what a user inputs Example: x = 'no' while x != 'yes': x = input('do you want to stop?') How many times will the above loop run? ! Note: “while” loop is called “indefinite loop” because you can start the loop without knowing in advance the number of iterations 8 Infinite Loops An infinite loop is a loop that will run forever because the condition will never resolve to False Example: while 1 < 2 x=0 while x < 3: print (x) Forgot 9 something? n=5 An Infinite Loop No Yes n>0? print 'Lather' n=5 while n > 0 : print 'Rinse' print ('Lather’) print ('Rinse‘) print ('Dry off!‘) print 'Dry off!' What is wrong with this loop? n=0 Another Loop No Yes n>0? print 'Lather' n=0 while n > 0 : print 'Rinse' print ('Lather’) print ('Rinse‘) print ('Dry off!‘) print 'Dry off!' What does this loop do? Indefinite Loops While loops are called "indefinite loops" because they keep going until a logical condition becomes False We can write a loop to run once for each step or iteration as per the initial condition using the Python while construct Indefinite loops can be easily wrongly constructed as infinite loops if the condition was not correctly designed. The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be "infinite loops" Definite Loops Quite often we have a list of items or effectively a finite set of things (numbers, letters, strings, …etc) We can write a loop to run the loop once for each of the items in a set using the Python for construct These loops are called "definite loops" because they execute an exact number of times We say that "definite loops iterate through the members of a set" for VS while LOOPS for loops while loops known number of iterations: unbounded number of iterations: No. of iterations is No. of iterations is not determined determined in the loop in the loop statement, the loop statement, the loop remains remains iterating until the condition iterating until this number is fails finished can end early via break can end early via break can use a counter to control the uses a counter that is iterations but must initialize automatically incremented before loop and increment it inside until the defined number of loop. iterations is finished may not be able to rewrite a 14 can rewrite a for while loop using a for loop loop using a while loop A Simple Definite Loop 5 4 for i in [5, 4, 3, 2, 1] : 3 print (i) 2 print ('Blastoff!‘) 1 Blastoff! Lists A list is an ordered sequence of values enclosed in square brackets List elements can be of any data type Examples: L1 = [1, 2, 3] L2 = ["a", "b", "c"] L3 = [1, "hello", 3.5] 16 List Operations: Concatenation The + operator can be used to join 2 lists Example: >>> L1 = [1, 3] >>> L2 = [2, 4] >>> L3 = L1 + L2 >>> print L3 [1, 3, 2, 4] 17 List Operations: Repetition Repetition builds a list by multiple concatenations of a list with itself We can repeat a list using the * operator Example: >>> * 3 [1, 1, 1] >>> ["hi", 1] * 2 ["hi", 1, "hi", 1] 18 List Operations: Indexing Indexing is used to access the individual elements of a list Items in a list are indexed from 0 to the length of the list - 1 Example: >>> L1 = [10, 20, 30] >>>L1 10 >>>L1 IndexError: list index out of range Note: unlike Strings, Lists are mutable i.e. you can edit a list Example: >>> L1 = "hi" >>> print L1 19 >>> [10, ‘hi’, 30] List Operations: Length Python provides a built-in function called len that returns the number of items in a list Example: >>> L1 = ["a", "b", "c", "d", "e"] >>> len (L1) 5 Empty >>> L2 = [] list >>> len (L2) 0 20 List Operations: Max, Min and Sum Python provides built-in functions to calculate the max, min and sum of list items Example: >>> L1 = [2, 10, 5, 1] >>> max (L1) 10 >>> min (L1) 1 >>> sum (L1) 18 Do experiment with a list of varied data types and see how Python will behave!! 21 List Operations: Slicing Slicing is used to access a slice from a list Slicing takes the form list[start : end : step] Including start and excluding end Example: >>> grades = [60, 70, 50, 80, 100] >>> grades [1:3] [ 70, 50] -5 -4 -3 -2 -1 >>> grades [2: ] 60 70 50 80 100 [50, 80, 100] 0 1 2 3 4 >>> grades [ :4:2] [60, 50] >>> grades[-1:-5:-1] 22 [100, 80, 50, 70] List Operations: Aliasing An alias is an alternative name for something A list can have multiple aliases all referring to the same values in memory Example: >>> L1 = [1, 2, 3] L1 >>> L2 = L1 >>> L2 = 4 1 42 3 >>> print L1 L2 [1, 4, 2] 23 What if I need to copy this list contents to another list at different memory location? List Methods L1 = [1, 3, 2, 4] list.append (x) Adds an item (x) to the end of the list Example: L1.append(5) => L1 = [1, 3, 2, 4, 5] list.insert(i, x) Insert x into list at index i Example: L1.insert(3, 9) => L1 = [1, 3, 2, 9, 4, 5] 24 List Methods list.reverse() Reverses the list in place Example: L1.reverse() => L1 = [5, 4, 9, 2, 3, 1] list.index(x) Returns index of first occurrence of x Example: L1.index(4) => 1 25 List Methods list.sort () Sorts the list in place Example: L1.sort() => L1 = [1, 2, 3, 4, 5, 9] list.count(x) Returns the number of occurrences of x in list Example: L1.count(9) => 1 26 List Methods list.remove(x) Deletes the first occurrence of x in list Example: L1.remove(2) => L1 = [5, 4, 3, 9, 1] list.pop(i) Deletes the ith element of the list and returns its value Example: L1.pop(2) => L1 = [5, 4, 9, 1] 27 Traversing a List for loops are also used to traverse a list one item at a time Example fruits = ["banana", "peach ", " strawberry "] for x in fruits: Output: print (x) banana peach strawberry 28 The “for” Loop iterating in a sequence “for loops” are used to traverse a sequence It has the following form: for in : Note the Indent Example of sequences is numbers, string , list Note: “for” loop is called “definite loop” because you cannot start the loop without knowing in advance the number of iterations 29 Looping on lists You can use loop to traverse all items in a list Example: L1 = [1,2,3,4] x=0 while x < len(L1): L1[x] = L1[x] * 2 x=x+1 print (L1) 30 while and for LOOPS iterate through numbers in a sequence # more complicated with while loop n=0 while n < 5: print(n) n = n+1 # shortcut with for loop for n in range(5): print(n) 31 Traversing a String You can traverse a string one character at a time using “for loop” Example: fruit = “banana” For loop While loop for x in fruit: i=0 print (x) while i < len(fruit): print (fruit[i]) i=i+1 32 Traversing a List “for loops” are also used to traverse a list one item at a time Example fruits = [‘banana’, ‘peach’, ‘strawberry’] For loop While loop for x in fruits: i=0 print (x) while i < len(fruits): print (fruits[i]) i=i+1 33 The “range” function Python provides a built-in function called “range” that generates a list of numbers It has the following format: range (start, end, step) Including start and Example excluding end >>> range (1, 5) [1, 2, 3, 4] >>> range (4) [0, 1, 2, 3] >>> range (7, 1, -2) [7, 5, 3] 34 Using “range” with “for” Since “range” returns a list of numbers, then you can use it with a “for” to loop over a sequence of numbers Example: for i in range(1, 6): print (‘#’ * i) 35 range(start,stop,step) default values are start = 0 and step = 1 ( optional ) loop until value is stop - 1 mysum = 0 for i in range(7, 10): mysum += i print(mysum) i mysum = mysum+i 7 0+7 36 8 0+7+8 9 0+7+8+9 range(start,stop,step) mysum = 0 for i in range(5, 11, 2): mysum += i print(mysum) i mysum = mysum+i 5 0+5 7 0+5+7 9 0+5+7+9 37 Looping a loop! Nested loops are loops inside loops This results in a full set of iterations for the inner loop, for every iteration of the outer loop Example: x=1 while x < 3: y=2 while y < 5: print (x * y) y=y+1 38 x=x+1 Looping a loop! Nested loops are loops inside loops This results in a full set of iterations for the inner loop, for every iteration of the outer loop Example: for c1 in "AB" : Output: AX for c2 in "XYZ": AY print (c1, c2) AZ c1 c2 Output on Screen BX X AX BY A Y AY BZ Z AZ X BX 39 B Y BY Z BZ Some common Loops Applications Let us CODE !! 40 Counting in a Loop z=0 $ python countloop.py print ('Before', z) Before 0 for thing in [9, 41, 12, 3, 74, 15] : 19 z=z+1 2 41 print (z, thing) 3 12 print ('After', z) 43 5 74 6 15 After 6 To count how many times we execute a loop we introduce a counter variable that starts at 0 and we add one to it each time through the loop. Summing in a Loop $ python countloop.py z=0 Before 0 print ('Before', z) 99 for thing in [9, 41, 12, 3, 74, 15] : 50 41 z = z + thing 62 12 print (z, thing) 65 3 print ('After', z) 139 74 154 15 After 154 To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop. Finding the Average in a Loop count = 0 $ python averageloop.py sum = 0 Before 0 0 print 'Before', count, sum 199 for value in [9, 41, 12, 3, 74, 15] : 2 50 41 count = count + 1 3 62 12 sum = sum + value 4 65 3 print (count, sum, value) 5 139 74 print ('After', count, sum, sum//count) 6 154 15 After 6 154 25 An average just combines the counting and sum patterns and divides when the loop is done. Filtering in a Loop print ('Before’) $ python search1.py for value in [9, 41, 12, 3, 74, 15] : Before if value > 20: Large number 41 print ('Large number', value) Large number 74 print ('After‘) After We use an if statement in the loop to catch / filter the values we are looking for. Search Using a Boolean Variable $ python search1.py found = False Before False print ('Before', found) False 9 for value in [9, 41, 12, 3, 74, 15] : False 41 if value == 3 : False 12 found = True True 3 print (found, value) True 74 print ('After', found) True 15 After True If we just want to search and know if a value was found - we use a variable that starts at False and is set to True as soon as we find what we are looking for. Search Using a Boolean Variable found = False print ('Before', found) $ python search1.py for value in [9, 41, 12, 3, 74, 15] : Before False if value == 3 : False 9 found = True False 41 break False 12 print (found, value) After True print ('After', found) If we just want to search and know if a value was found - we use a variable that starts at False and is set to True as soon as we find what we are looking for. What is the Smallest and Largest Number in a list? The "is or ==" and "is not or !=" Operators smallest = None Python has an "is" operaror that print ('Before’) can be used in logical for value in [3, 41, 12, 9, 74, 15] : expressions if smallest is None : smallest = value Implies 'is the same as' elif value < smallest : smallest = value Similar to, but stronger than == print (smallest, value) print ('After', smallest) 'is not' also is a logical operator Breaking a loop A “break” statement is used to exit a loop even if it didn’t reach its final iteration. Example: Output: for char in "Apple" : A if char == 'l': p p break Exit the loop else: print (char) 49 Breaking Out of a Loop The break statement ends the current loop and jumps to the statement immediately following the loop It is like a loop test that can happen anywhere in the body of the loop while True: > hello there line = input('> ') hello there if line == 'done' : > finished break finished print (line) > done print ('Done!‘) Done! Breaking Out of a Loop The break statement ends the current loop and jumps to the statement immediately following the loop It is like a loop test that can happen anywhere in the body of the loop while True: > hello there line = input('> ') hello there if line == 'done' : > finished break finished print (line) > done print ('Done!‘) Done! while True: line = input('> ') No Yes True ? if line == 'done' : break.... print (line) print ('Done!‘) break... print 'Done' Finishing an Iteration with continue The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration while True: > hello there line = input('> ') hello there if line == '#' : > # don't print this continue > print this! if line == 'done': print this! break > done print (line) Done! print ('Done!‘) Finishing an Iteration with continue The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration while True: > hello there line = input('> ') hello there if line == '#' : > # don't print this continue > print this! if line == 'done': print this! break > done print (line) Done! print ('Done!‘) No True ? Yes while True: line = input('> ’).... if line == '#' : continue if line == 'done' : continue break print (line)... print ('Done!‘) print 'Done' Write a program that takes a list L and removes every even number in it and print the SAME list after removing those numbers. >>[1,2,3,4,5,6] [1, 3, 5] Write a program that takes a number N from user and sum every odd number from 1 to N using For Loop Write a program that takes a number and prints how many times we can divide it by 2 to get down to 1 (3 Marks) >>13 3 Write a program that takes a list L and prints the count of float numbers in L. (3 Marks) >>[1.3,2.0,-1, “5”,6.43] 3 Introduction to “Making Choices” 1 Outline string object type Why use Choices Boolean expression Logical operators branching and conditionals If Statement Nested if statement indentation Storing Conditions 2 Why Strings? Many programs depend on string usage and manipulation An example problem: Write a program to emulate an intelligent ChatBot… To solve a problem like that, you need to learn about strings What is a String? A string is a sequence of letters, special characters, spaces, digits Strings are delimited by single ‘ ‘ or double “ “ quotes Strings can be stored in variables Example: X = "hello there" Type(X)? >>> Str1 = “hello” >>> Name = ‘Ahmed’ >>> ‘that’ll not work’ SyntaxError: invalid syntax >>> “that’ll work” What if you want to put both kinds of quote in one string? Strings think of as a sequence of case sensitive characters can compare strings with ==, >, < etc. len() is a function used to retrieve the length of the string in the parentheses s = "abc" len(s) evaluates to 3 5 String Input Python provides input function called input() that does not evaluate the expression that the user types Example: >>> name = input() Ahmed >>> print (‘hello’, name) hello Ahmed >>> expression = input(“enter an expression: “) enter an expression: 3 + 2 - 1 >>> print( ‘x = ‘ + expression) x=3+2-1 Simple ChatBot Believe it or not! That’s all you need to know to solve the problem given at the beginning. Here is the code: print( "Hi There...") print( "What's your name?") name = input("My name is: ") print( "Nice to meet you " + name) print( "How are you feeling today?") feeling = input("I am feeling ") print( "Glad you are feeling " + feeling ) print( "It was nice meeting you " + name+ ". Hope you have a very nice day!") print( "Have fun in CSCE 201 today ;-) ") But there is still soooo much more String Operations: Repetition Repetition builds a string by multiple concatenations of a string with itself We can repeat a string using the * operator Example: >>> ‘hi’ * 3 ‘hihihi’ >>> ’12’ * 2 ‘1212’ String Operations: Concatenation X = "hello there" concatenate strings Y = “ANN" greet = X + Y greeting = X + " " + Y Code= 456 greetings = X + " " + Y + “your code is, “ + Code What Happened Here? How to solve this problem 1- ? String Operations: Length Python provides a built-in function called len that returns the number of characters in a string Example: >>> name = “Bob” >>> len (name) 3 >>> len (‘hello’) 5 String Printing 1. Escape Characters Escape characters are used inside a string to “escape” from Python’s usual syntax rules for a moment Example: >>> print( ‘she said, “that is hard to read”’) she said, ”that is hard to read” >>> print( ‘she said, “that\’s hard to read”’) she said, ”that's hard to read” >>> print (“hello \n world”) hello world String Printing 2. Multiline String If you create a string using single or double quotes, it must fit on a single line Example: >>> ‘one EOL while scanning string literal To span multiple lines, put three single quotes or three double quotes Example: >>> ‘’’one … two … three’’’ ‘one\ntwo\nthree’ String Printing 3. Formatted Printing To print the value of a variable with a string we can use 1. Comma-separation >>> p = 3 >>> print (“price =“, p, “$”) price = 3 $ Comma-separated strings will be separated by a space 2. Concatenation >>> name = ‘Ahmed’ >>> print (‘welcome ’ + name) Concatenation can only be welcome Ahmed used between 2 strings >>> print (“price =“ + p + “$”) TypeError: cannot concatenate 'str' and 'int‘ String Printing %d Integer 3. Formatted Printing %f Float %s String 3. String formatting >>> p = 5 >>> t = 34.5 >>> c = ‘Egypt’ >>> print (“price = %d” %(p)) price = 5 >>> print (“temp in %s = %f degrees” %(c,t)) temp in Egypt = 34.500000 degrees Indicates precision >>> print (“temp in %s = %.1f degrees” %(c,t)) temp in Egypt = 34.5 degrees Indicates width >>> print (“temp in %s = %100.1f degrees” %(c,t)) temp in Egypt = 34.5 degrees Casting (Type Conversion) In Python you can convert a variable from a type to another To get the type of a variable use the type(var) function Example: >>> x = 3 >>> type(x) To convert x to a float use the float(var) function Example: >>> x = float(x) >>> type(x) float (expr) Convert expr to a floating point value >>> str (1 + 3) int (expr) Convert expr to an integer value ‘4' str (expr) Return a string representation of expr Evaluating Strings Python provides a function eval(expr) used to evaluate a string as an expression Example: >>> eval (‘1 + 4 * 2’) 9 >>> eval (‘3.5 – 1‘) 2.5 Note that int() is used for conversion not evaluation >>> int (‘1+5’) ValueError: invalid literal for int() Evaluating Strings What if expression is not an expression Note that some characters are in Example: the eval expression >>> eval (‘1 + hi * 2’) NameError: name 'hi' is not defined INPUT/OUTPUT: print( ) (recap) used to output stu