






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
How to define a function named 'dscore' in python, which takes a string as an argument and returns the difficulty score represented in the string. The anatomy of a function definition, the role of parameters, and the importance of specifications and preconditions. It also discusses testing and debugging techniques.
Typology: Slides
1 / 10
This page cannot be seen from the preview
Don't miss anything!







Given : info contains a comma-separated string with last name, difficulty, execution, and penalty. § Example: info = 'RAISMAN, 6.7, 9.1,0' Goal : store the difficulty as a string, with no extra spaces or punctuation, in variable df Users (including other programmers) want to write things like: raisman_df = gym.dscore('RAISMAN, 6.7, 9.1,0') print gym.dscore(' PONOR , 6.2 , 9.0 , 0') The function dscore is in module (file) gym. When called, it returns a value that the user can utilize as they wish.
"""Returns: difficulty score, as a float, represented in info. Precondition: info is a string with commas separating its component values: last name, difficulty score, execution score, penalty.""" startcomma = info.index(',') tail = info[startcomma+1:] # part of info after 1st , endcomma = tail.index(',') return float(tail[:endcomma].strip()) def dscore(info) :
header In file gym, we define dscore as follows. declaration of parameter (variable) named "info" body ( indented ) specification, as a docstring Return statement (optional). Contains expression whose value results from the function call.
def dscore(info): """Returns: difficulty score, as string, represented in info. Precondition: info is a string with commas separating its component values: last name, difficulty score, execution score, penalty.""" startcomma = info.index(',') tail = info[startcomma+1:] # part of info after 1st , […] Single summary line, followed by blank line. (More detail can be added in separate paragraphs) Precondition: assumptions about the argument values
§ 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.
§ Preconditions not documented properly § Functions used in ways that violate preconditions
def test_last_name_first(): """Test procedure for last_name_first(n)""" cunittest.assert_equals('White, Walker', last_name_first('Walker White')) cunittest.assert_equals('White, Walker', last_name_first('Walker White'))
if name == 'main': test_last_name_first() print 'Module name is working correctly' Expected is the literal value. Message will print out only if no errors. Quits Python if not equal Received is the expression.