Lecture of 20th October at 9:15 (* What is the type of a range, and a list of a range? *) >>> type(range(10)) >>> type(list(range(10))) (* Some examples of range syntax *) >>> range(5,10) >>> list(range(5,10)) >>> list(range(5,10,2)) (* How do we print a range in reverse? *) >>> list(range(10,0)) >>> list(range(10,0,-1)) (* Looping over a list using a for loop *) >>> a = ['Mary','had','a','little','lamb'] >>> for i in range(len(a)): >>> print(i, a[i]) (* An infinite loop that does not crash as it consumes no memory. Will not compile, however*) >>> while True: pass (* Implementing a dictionary (Similar to a hash map in java) *) >>> superman_todo = { 1:"Get out bed", 2:"Save world", 3:"Have breakfast"} >>> s = superman_todo >>> s[1] (* What values do these functions return? *) >>> s[4] >>> s.get(4) (* What does the following function print out? Why? *) >>> if s.get(4): ... print("Hello") ... else: ... print("Goodbye") (* Creating an essentially empty dictionary *) >>> t = { 1:None } >>> t.get(1) >>> t.get(2) (* What does this function print out now? *) >>> if t.get(1): ... print("Hello") ... else: ... print("Goodbye") (* This is a fibonacci procedure. It is called a procedure, as it returns the value None. (There is no return) *) >>> def fib(n): ... a,b=0,1 ... while b < n: ... print() ... a,b=b,a+b (* What is the type of this procedure? *) >>> fib (* The function help tells us more about the function we're using*) >>> def obscurefunction(n): ... """Multiplies n by 2""" ... return 2*n >>> help(obscurefunction) (* What will this function return? *) >>> def bla(l): ... l = [] ... >>> l = ["not","empty"] >>> bla(l) >>> l (* This function, however, does edit the contents of l. How? *) >>> def exclamate(l): ... l.append("!") ... >>> exclamate(l) >>> l (* What is the output of exclamatebla? *) >>> def exclamatebla(l) ... l.append("!") ... l = [] >>> l = ["not","empty"] >>> exclamatebla(l) >>> l (* What if we use clear() instead? *) >>> def exclamatebla(l) ... l.append("!") ... l.clear() >>> l = ["not","empty"] >>> exclamatebla(l) >>> l (* Changing the index works by reference, changing the list itself works by value. What should this function return? *) >>> def crazyfun(l) ... l[0]="Joanne" ... l = [] >>> l = ["Jamie"] >>> crazyfun(l) >>> l (* This function asks for the global value of l, rather than the local one. *) >>> def clear_l(l): ... global l ... l = [] (* What does this output then? *) >>> l = ['not','empty'] >>> clear_l(l) >>> print(l)