170 likes | 270 Views
CISC 101: Fall 2011. Hossain Shahriar shahriar@cs.queensu.ca. Announcement and reminder !. First quiz tomorrow/next Monday, let me know! No class on Wednesday and Thursday of next week We will figure out a suitable time for a makeup class
E N D
CISC 101: Fall 2011 HossainShahriar shahriar@cs.queensu.ca
Announcement and reminder! • First quiz tomorrow/next Monday, let me know! • No class on Wednesday and Thursday of next week • We will figure out a suitable time for a makeup class • I will handout Assignment 1 on Monday so that you can finish them by end of next week! • We will have total six take home assignments and each of them will have 1.5 marks • Tentative date for final exam need to be fixed! • Topics to be covered in this lecture(s) • If-else statement • Loop • Exception handling • As a side, we will see some useful functions for string and list
Python shell and file • In the GUI, open a new file and save it as a reasonable name with an extension .py • We can write the code in the class • Press F5 to see the result in the GUI
If-else • If expr1 : • Statement1 • elif expr2: • Statement2 • elif expr3: • Statement3 • else: • Statement4
If-else usage with situations • Case 1: we only need to test one thing • E.g., testing if a number is negative or not • If x < 0: • print x, ‘is negative’ • E.g., testing which of the two number (x, y) are bigger • If x > y: • print x, ‘ is bigger’ • Else: • Print y, ‘ is bigger’
If-else usage with situations (cont.) • Case 2: we need to test at least two things to have a conclusion • E.g., testing the highest numbers among three (x, y, z) • We are heading to nested if-else structure!! • If x > y: • If y > z : • print y, ‘ is bigger’ • else: • print z, ‘ is bigger’ • … can you complete the rest !! (take home assignment)
Loop • Sequence of similar operations can be performed by a loop • E.g., sum the sequence 1+2+ 3+ ..5 • Imagine, there is no loop structure in a language and we are only allowed to use if-else • The solution would be • var x =1 • x = x+ 2 • x= x+3 • x= x+4 • x= x+5 • It will work, but it seems doing similar stuff each of the last four lines! • We could rather use 2 lines of code to do the same thing!! • How?
Loop (cont.) • We will learn two types of loop structure: for, while • for x in [list]: • statement • Here, x is an iterating variable that will assume the value sequentially one after another • All we should think is controlling • The initial and final value of x • The statement that will make the job done for us
Loop (cont.) • Let us revisit the last example of summing the series 1 + 2+ 3+ … 5 • sum = 0 • for x in range(5) : • sum = sum + x • Here, range (n) is a built in method that generates lists containing arithmetic progressions • E.g., range (5) = [0, 1, 2, 3, 4, 5] • range(5, 10) = [5, 6, 7, 8, 9, 10] • Take home assignment: what happens if we use range(-5)? Experiment all by yourselves and let me know in next class.
Loop (cont.) • More examples where for loop is handy • E.g., assume we have a set of random numbers where each number ranges between -10 and +10 [3, 5, -3, 7, 0, -2, 9, 8] • Can we calculate the average of the set? • Imagine, we have a list of names ['Mary', 'had', 'a', 'little', 'lamb'] • Can we know which of the name is the longest? • Tips: we need not only to access each of the element, but also test the elements for the interesting property we are looking for! • Now we are heading to a problem that requires combining both loop and if-else structure
Loop (cont.) • The length of a list need to be known to go through each of the element • len (list) • How to access each element? • list[i], where i is the index starts from zero • list = ['Mary', 'had', 'a', 'little', 'lamb'] • list[0] = ‘Mary’ • list[1] = ‘had’ • list [4] = ‘lamb’ • How to check the length for each string? • len (‘Mary’) will return 4 • len (list[0]) will return 4 • Note that we are using lenfor obtaining length of a list and length of a string!!
Loop (cont.) • So, we are pretty much ready to find a solution. • list = ['Mary', 'had', 'a', 'little', 'lamb'] • max_len = 0 • element = ‘’ • for x in len(list): • if len (list[x]) > max_len: • element = list[x] • print ‘Highest length:’, max_len, ‘, element name:’, element
Loop (cont.) – Break, continue statement • Useful in certain situations and often used in an if-else structure within a loop • Imagine, we want to iterate a list to find at least one negative number • We do not need to continue the loop once we find a case • for x in len (list) • If x < 0: • Print ‘found a negative number, goodbye!’ • break • Caution: if you have multiple loops, then break will only affect the immediate loop where it is located • For …. : #loop1 • For … : #loop2 • If … break # break loop2 only and loop1 will continue as usual
Loop (cont.) – Break, continue statement • Continue is useful if we want to avoid execution of specific portion of a for loop • all the statements that you write after continue • Vagabond style programming: We start with the code pattern that we know but not sure where it will end up • Imagine, we are writing a for loop and there are so many checks required in one iteration • You are using lots of if-else in a loop and somehow discovered that each of the if-else is independent from each other – good news! • If one of them actually becomes true, then none of remaining will not be true • You can safely skip the execution of remaining if-else with continue
Loop (cont.) – Break, continue statement • for x in len (a): • If x > 0 && x < 5: • Statement… • Continue # skip the rest of the code and go to the beginning of loop • If x > 5 && x < 10: • … • If x > 10 && x < 15: • … • If x > 15 && x < 20: • … • Please read lecture slides and sections 4.1-4.4 from http://docs.python.org/tutorial/controlflow.html to prepare for the next quiz
Exception handling • A generic way to handle incompatible input • E.g., a user provides string instead of a number • def main(): • try: • x = int (input ("enter a number : ")) • … • except Exception: • print "The supplied input is not a number" • main()
Exception handling (cont.) • A user provides a filename that does not exist or cannot be open for reading and writing • Take home assignment • Can you write a function that opens a file for reading and throws exception if it cannot open it?