Lecture 1 - DePaul University



CSC 401 NotesLecture #3Yosef MendelsohnGetting / Creating Documentation for functionsNearly all of Python's built-in functions have documentation that can be viewed with the help() function.For example, suppose you wanted documentation on how to use the len() function:>>> help(len)Help on built-in function len in module builtins:len(...) len(object) -> integer Return the number of items of a sequence or mapping.>>> help(min)Help on built-in function min in module builtins:min(...) min(iterable[, key=func]) -> value min(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its smallest item. With two or more arguments, return the smallest argument.Unfortunately, the help function does not provide useful information about programmer-defined functions (i.e. the functions created by programmers that are not built-in to Python). However, we as programmers can – and should – include information about our functions that will be available with the help() function. For example, we can see what it displays when we ask about a function add5 we defined in the previous section:>>> help(add5)Help on function add5 in module __main__:add5(x)As you can see, we really don't get any useful information here. However, when defining (i.e. creating) a function, a good programmer will always provide at least some kind of documentation for that function. If this is done in a particular way which we will learn about, this information will be available to anybody who uses your function by simply typing the help() command. The simplest way is as follows: Simply add a string below the def statement:def add5(x):'''returns the value of x+5'''return x+5Note that we can use single or triple quotes. I tend to use triple quotes because it is sometimes necessary to add more than one line of explanation.Now when we call the help function on the method, we will get the string we have added:>>> help(add5)Help on function f in module __main__:add5(x) returns the value of x+5Exercises: In addition to the required code, be sure to also write a brief (single line) help statement for each. Write a personalized hello function called greetUser() that takes as a parameter a name represented as a string and returns the string “Hello <name>”Write a function called printParity() that takes as a parameter a list of numbers and prints, onto the screen and one per line, the values in the list. The odd values should have a label “odd” in front of them, and the even values should have a label “even” in front of them. NOTE: This function prints things. It is there for practice, but recall that in the 'real world', functions don't typically print things. The only reason we are printing here is that it makes it easy to see if our function is behaving the way we want it to.Write a function called printFour() that takes a list of strings as a parameter and prints all of the strings of length four to the screen, one per line.Again: This function prints things. It is there for practice, but recall that in the 'real world', functions don't typically print things. ?Solutions:def greetUser(name): '''greets the user''' s = 'Hello, ' + name + '.' return s#TEST: #print(greetUser('Bob'))def printParity(lstNumbers): '''prints all numbers preceded by odd or even''' for number in lstNumbers: if number%2==0: print('Even: ',number) else: print('Odd: ',number)#TEST:#printParity( [3,4,5,6,7,22,33] )def printFour(lstStrings): '''prints only those strings of length 4''' for s in lstStrings: if len(s)==4: print(s)#TEST:#strings = ['hi','heya','howdy','ssup','hola','bonjour','allo']printFour(strings)Strings continued:Recall from an earlier discussion that proficiency in working with Strings is vital in many aspects of programming. Python has many built-in functions for manipulating strings. Assume that some variable 's' has been assigned a string value. The following are some useful string functions:s.count(target): Returns the number of occurrences of the substring target in ss.find(target): Returns the index of the first occurrence of the substring target in ss.lower(): Returns a copy of the string s converted to lowercases.upper(): Returns a copy of the string s converted to uppercases.isupper(): Returns True if the string is in upper cases.islower(): Returns True if the string is in lower cases.replace(old, new): Returns a copy of the string s in which every occurrence of substring old is replaced by news.split(sep): Returns a list of substrings of the string s, obtained using the delimiter string sep; the default delimiter is a spaceWe demonstrate a few of these below:>>> s = 'hello world'>>> s.find("world")6>>> s.replace("world", "universe")'hello universe'#Question: What would happen if #instead of the above line, we typed:# s = s.replace("world", "universe") >>> s'hello world'>>> s.split()['hello', 'world']>>> s'hello world'>>> s.upper()'HELLO WORLD'>>> s'hello world'>>> s.count('hell')1>>> s.count("o")2>>> s.count("low")0The method split is particularly useful for parsing a line text into a list of individual words. This kind of thing comes up surprisingly often in the real world. Practice problem:Assign to a variable 'forecast' the string ‘It will be a sunny day today’ and then write Python statements to do the following:Assign to a variable count the number of occurrences of the string ‘day’ in forecastAssign to a variable weather the index where the substring ‘sunny’ startsAssign to a variable change a copy of forecast in which every occurrence of the substring ‘sunny’ is replaced by ‘cloudy’forecast = 'It will be a sunny day today'c = forecast.count('day')print(c)weather = forecast.find('sunny')print(weather)change = forecast.replace('sunny','cloudy')print(change)There are many more string functions available then are described here. See Table 4.1 on page 101 of the textbook for a partial listing. To see them all, remember the handy 'help' function discussed previously:>>> help(str)Help on class str in module builtins:class str(object) | str(string[, encoding[, errors]]) -> str | | Create a new string object from the given encoded string.…Numeric typesWe talked about numeric types (integer, floats, etc.) and some of their properties previously. We need to review some of the concepts we touched on again.Type conversionsIf an expression involves operands of numeric types, Python will convert each operand to the most “complex” type.Some examples are given below:>>> 3 + 0.253.25>>> a = 3>>> b = 0.25>>> c = a+b>>> type(c)<class 'float'>Casting between typesWe can explicitly cast between compatible types:>>> x = 3.1415>>> y = int(x)>>> y3>>> x = '1234'>>> y = int(x)>>> y1234>>> y = 1234>>> x = float(y)>>> x1234.0Not surprisingly, some castings are not possible. In this case, an exception will be generated:>>> x='hello'>>> int(x)Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> int(x)ValueError: invalid literal for int() with base 10: 'hello'One thing to be aware of just for future reference, is that the boolean value can sometimes be interchanged with the value 1, and False can be interchanged with the value 0. This does have application in certain programming situations.>>> x=bool(1)>>> print(x)True>>> y=bool(0)>>> print(y)FalseOperators and precedence rulesRecall: An expression is a combination of numbers (or other objects) and operators that is evaluated by the Python interpreter to some literal (i.e. a value).As a review, below is a list of common Python operators. All of the operators are shown in order of precedence from highest to lowest. For example, if in an expression you have a '+' and a '&', then the plus operator will be evaluated before the '&' because it has higher precedence. Precedence TableHighest precedence is at the top. OperatorDescription(expressions...), [expressions...], {key:datum...}, `expressions...`Binding or tuple display, list display, dictionary display, string conversionx[index], x[index:index], x(arguments...), x.attributeSubscription, slicing, call, attribute reference**Exponentiation [8]+x, -x, ~xPositive, negative, bitwise NOT*, /, //, %Multiplication, division, remainder+, -Addition and subtraction<<, >>Shifts&Bitwise AND^Bitwise XOR |Bitwise OR in, not in, is, is not, <, <=, >, >=, <>, !=, ==Comparisons, including membership tests and identity tests,not xBoolean NOTandBoolean ANDorBoolean ORlambdaLambda expressionExercise: Explain in what order the operators in the expressions below are evaluated:3+2*4Because the '*' has higher precedence than '+', we will first do the multiplication, followed by the addition.Not surprisingly, the precedence rules for mathematical operations in Python follow the standard precedence rules that you probably learned in high school math. (Parentheses > Exponents > multiplication/division > addition/substraction, etc)2*3**2Exponentiation (32)Multiplication (multiply the 9 from the previous step times 2)2+3 == 4 or a >= 5Addition== comparison>= comparison'or' operationNOTE: Note that >= and == have the same precedence. When this happens, the operator on the left-most side of the expression is evaluated first. Single, double, and triple quotesA string is represented as a sequence of characters that is enclosed within either double or single quotes. There is also a use for triple quotes. To construct a string that contains quotes, we can use the opposite type of quotes, e.g. using single quotes within double quotes or double quotes within single quotes.>>> excuse = 'I am "sick"'>>> excuse'I am "sick"'>>> fact = "I'm sick">>> fact"I'm sick"If text uses both type of quotes, then the escape sequence \’ or \” is used to indicate that a quote is not the string delimiter but is part of the string value.>>> excuse = 'I\'m "sick"'>>> excuse'I\'m "sick"'>>> print(excuse)I'm "sick"If we want to create a string that goes across multiple lines, we can use triple quotes.>>> quote = '''This poem isn't for youbut for meafter all.'''>>> quote"\nThis poem isn't for you\nbut for me\nafter all.\n">>> print (quote)This poem isn't for youbut for meafter all.The print() functionIt is possible to output multiple items in the print function. The default separator between items is a blank space.print('hello','goodbye',45)Will output: hello goodbye 45>>> n = 5>>> r = 5/3>>> print(n,r)5 1.66666666667>>> name = 'Ada'>>> print(n,r,name)5 1.66666666667 AdaIf, when using the print() function, we wish to use something other than a space, we can use the optional argument sep to indicate what the separator should be.For example, if we wanted to separate the items above with three forward slashes instead of a blank space, we would write:>>> print(n,r,name,sep='///')5///1.66666666667///AdaNormally successive calls to the function print() will output on a separate line:>>> for name in ['Marisa', 'Sam', 'Tom', 'Anne']:print(name)MarisaSamTomAnneThe print() function also supports the optional argument end .When the argument end = <some string> is added to the arguments to be printed, the string <some string> is printed after each argument.>>> for name in ['Marisa', 'Sam', 'Tom', 'Anne']:print(name, end="! ") #Note the space after the '!' characterMarisa! Sam! Tom! Anne! sep v.s. end ‘sep’ is what you use to separate one item from the next inside the print() functionprint('hello', 'goodbye',45, sep=' ') will separate the 3 items by two spaces: hello Goodbye 45‘end’ will append to the end of each item:print('hello', 'goodbye',45, end='?') will append a question mark after each: hello? Goodbye? 45?Exercise: Use the help() function to see the help notes for the print() function:help(print)In particular, note the following:Some arguments are optional. That is, when you invoke this function, you are not required to provide those arguments unless you want to. Some arguments – typically the optional ones - have a default value. For example, the default value for the ‘end’ argument is a new line. The default value for the ‘sep’ argument is a space.String Formatting Methods There are many useful techniques for formatting output so that it appears in ways that are meaningful. The techniques for doing so take a little getting used to, but it is definitely worth getting to know the basics.We can exert some control over the apperance of output using the format() method.It can be a bit confusing to describe, so we won't spend much time doing so now. Instead, we will demonstrate with a few examples. Your textbook will, of course, give you plenty of detail to explain how it works. We call these elaborate formatted strings format strings.As mentioned, we create a format string by invoking a function (technically, a 'method' – more on this distinction later) called format. We invoke the format method by preceding the method call with a string. This string represents the format that we want the output to take. The arguments to the format method are the objects we wish to output.>>> hour = 11>>> minute = 45>>> second = 33>>> '{0}:{1}:{2}'.format(hour, minute, second) #Note the colonsOutputs: '11:45:33'The 0 represents the first argument to the format method (in this case, the hour), the 1 represents the second argument (i.e. minute), and the 2 represents the third argument (i.e. second).>>> '{2}:{0}:{1}'.format(hour, minute, second)Outputs: '33:11:45'In this case, by switching the indexes inside the curly braces, we can modify the order in which the arguments to format are printed.You can also use a call to the format method inside of a call to the print function.>>> weekday = "Friday">>> month = "March">>> day = 10>>> year = 2017>>> print('{}, {} {}, {} at {}:{}:{}'.format(weekday, month, day, year, hour, minute, second))Outputs: Friday, March 10, 2017 at 11:45:33Also note in the above example: If do not specify numeric values inside the braces, the arguments to format are printed in the order in which they were passed to the function.Another example: Let’s create a format string to print a telephone number so that the area code is inside parentheses, followed by a space, and then print the prefix (first 3 numbers), then a dash, followed by the extension (last 4 numbers). For example: (area code) prefix-extension. E.g. (312) 555-6666>>> '({0}) {1}-{2}'.format('312','555','6666')'(312) 555-6666'Let’s create a function that will accept 3 arguments representing the area code, prefix, and extension, and output it in the above format. def phoneNumberOutputString(areaCode,prefix,extension): '''returns a string that looks like a formatted phone number''' s = '({0}) {1}-{2}'.format(areaCode,prefix,extension) return sLet’s test it: tmp = phoneNumberOutputString('312','555','6666')print(tmp)tmp = phoneNumberOutputString('312','867','5309')print(tmp)As you may have deduced, the format() method is invoked by a string that represents the format of the output. The arguments to the format function are the objects to be printed.Example: fn = 'Lisa' ln = 'Chen' print('Your first name is {0}'.format(fn) ) print('Your full name is: {1}, {0}.'.format(fn, ln)) print('Your full name in caps: {1}, {0}.'.format(fn.upper(), ln.upper()))Outputs:Your first name is BobYour full name is: Chen, Lisa.Your full name in caps: CHEN, LISA.Another Example:>>> day = 25>>> month = 1>>> year = 2017>>> '{1}/{0}/{2}'.format(day, month, year)'1/25/2017'#Let’s format using the European system:>>> '{0}/{1}/{2}'.format(day, month, year)‘25/1/2017’Start by looking at the arguments to the format() method. In the above examples, there are 3 of them. These arguments can be referred to using {0} for the first argument (day), {1} for the second (month) and {2} for the third (year). Notice that we invoke the format() method using a string. However, inside that string, we can refer to any of the arguments using the braces: { and }. You can also use a call to the format() method inside of a call to the print function.>>> weekday = "Wednesday">>> month = "January">>> day = 18>>> year = 2012>>> hour = 1>>> minute = 45>>> second = 33>>> print( '{}, {} {}, {} at {}:{}:{}'.format(weekday, month, day, year, hour, minute, second) )Wednesday, January 18, 2012 at 1:45:33You can line up data in columns. Let’s consider how to line up integers using the field width within the format string. We will discuss lining up non-integer values at a later point.Consider this code:for i in range(1,13): s = '{0} {1} {2} {3}'.format(i, i**2, i**3, i**4) print(s)Here is the output:1 1 1 12 4 8 163 9 27 814 16 64 2565 25 125 6256 36 216 12967 49 343 24018 64 512 40969 81 729 656110 100 1000 1000011 121 1331 1464112 144 1728 20736Obviously, it would be nice to force each item in the format string to occupy a certain number of characters. Let’s make all items take up 6 characters at a minimum. The way we do this is to type a a colon inside the braces function followed by the desired number of spaces to take up in each column:for i in range(1,13): s = '{0:6} {1:6} {2:6} {3:6}'.format(i, i**2, i**3, i**4) print(s)Here is the output: 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 10 100 1000 10000 11 121 1331 14641 12 144 1728 20736Note that by default, the output is right-justified. This can be changed by modifying various format string options.Let’s finesse things just a bit further by spacing on minimums (i.e. 2 characters for the first column, 3 for the second, 4 for the third, and 5 for the fourth). We will also separate each column from the next by two tabs:for i in range(1,13): s = '{0:2}\t\t{1:3}\t\t{2:4}\t\t{3:5}'.format(i, i**2, i**3, i**4) print(s)And the output: 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561101001000100001112113311464112144172820736Aside: f stringsThere is an alternative (and somewhat newer) way to format strings called f-strings. Feel free to check them out if you are interested. Here is a short article that discusses them. That being said, format strings are widely used and will be seen in a tremenodus amount of legacy code, so you should not neglect them. In this course, we will only discuss format strings, but you are certainly welcome to experiment with f strings if you are interested. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download