Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Announcements - handout Announcements References for today: 3.1-3.6 (functions); 4.9 (docstring for a function); 14.9 (writing a module) No reading for next time: Our treatment of objects differs significantly from the book's. Slides by D. Gries, L. Lee, S. Marschner, W. White last time From command sequences to functions Given: variable data contains a string with at least two ','s. Example: data="LL, '14, 1-800-OPYTHON, 1-555-TYPHOON" Goal: print the part of the string after the 2nd ',', stripping whitespace from ends. Put commands in file string_puzzle_soln.py At command line, type "python string_puzzle_soln.py" But users (including other programmers) want to write things like: gvr_phone = phone("GvR, '14, 1-800-OPYTHON") Can store output in a variable User not forced to have variable named data Can use the same function twice in one line phone(some_data_string) == phone(other_data_string) Calling a Function Already in a Module Example: fix the capitalization of words with two caps, like "THanks". Lucky us: someone has written a file string.py which defines a module string holding various functions. on some computers: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/string.py import string # Tell Python to we want access to this module. # DON'T say "string.py" or you'll get an error. # Built-in modules don't have to be in current dir. print string.capwords("THanks") specify that function capwords is from module string Anatomy of a Function Definition header body (indented) specification, as a docstring declaration of parameter (input variable) named s def capwords(s): """Returns: Title-cased copy of s. Example: "aBc dEf " -> "Abc Def" Precondition: s is a string""" temp = 5 return (sep or ' Return statement (optional). Contains expression whose value is to be the result from the ').join(x.capitalize() function call. for x in s.spli...) Writing a Function, Step One: Header and Specification Example input strings: 'RAISMAN, 6.7, 9.1,0' "Ponor, 7 , 9, 0" Single summary line, followed by blank line. (More detail can be added in separate paragraphs) def defdscore(info): dscore(info): """Returns: the difficulty score, as float, represented in info. Precondition: info is a string with commas separating its component values: last name, difficulty score, execution score, penalty.""" Precondition: assumptions about the argument values Parameters: Variables Holding Input Values def dscore(info): """Returns: difficultyWhen score,you as acall float,a function, represented insupply info. you arguments: input values. Precondition: info is aex: string with commas separating 6.7, its 9, 0') gym.dscore('Raisman, component values: last name, difficulty score,inexecution These values are stored the function's score, penalty.""" corresponding parameters: input variables used within the function. Ex: info startcomma = info.index(',') [...] A Specification is a Contract Preconditions are a promise that: § if the arguments satisfy the preconditions, the function works as described in the specification; § but, if the user's arguments violate the precondition, all bets are off. So write these contracts carefully! Common sources of software errors: § Preconditions not documented properly § Functions used in ways that violate preconditions Testing Program "Correctness" • • • • Bug: Error in a program. (Always expect them!) Debugging: Process of finding bugs and removing them. Testing: Process of analyzing, running program, looking for bugs. Test case: A set of input values, together with the expected output. Organizing Test Cases: Unit Tests A unit test is a module that tests another module. 1. It imports the other module (so it can access it) 2. It imports the cornelltest module (provided by us) 3. It defines one or more test procedures • • Evaluate the function(s) on the test cases Compare the result to the expected value 4. It has special code that calls the test procedures Example unit test excerpt: testgym.py Expected answer # test procedure The value produced goes first. def test_dscore (): by the function being """Test procedure for gym.dscore(n)""" tested goes second. cornelltest.assert_floats_equal(6.7, gym.dscore('Raisman, 6.7, 9.0, 0')) Quits Python Code below this line is executed if not equal we do "python testgym.py" on # Application code command line if __name__ == '__main__': test_dscore() Message printed out only print 'Module gym is working correctly' if all test cases pass (i.e., no test function causes an error) An Important, If Counterintuitive, Principle Write test cases for a function from its specification — even before writing the function’s body. def number_vowels(w): """Returns: number of vowels in word w. Precondition: w a string with at least one letter and only letters""" pass # nothing here yet! You need to be clear about what you're trying to solve before you try to solve it! (Unless you're doing research.) Debugging with Print Statements Print statements expose the values of variables, so you can check if they have the value you expect. print 'in this solution, df is "' + df + '"' Don't leave these in your finished code! They reduce readability.