Docstrings, preconditions, and postconditions A docstring is a triple-quoted string that appears right after a function header. Its audience is another program, or maybe you, a few months after you wrote the function. It is a brief reference describing what the function does.
A good way to manage this is to have two sections.
Preconditions These describe anything that shhould be true before the function is called. This can include a description of the number and types of inputs the function should have.
Postconditions These describe anything that should be true after the function is called. Here, describe any return value and any side-effects calling the function produces.
My function assignments will be speced in this way.
Whats up __doc__
? The standard functions
all have docstrings. Here we see some examples.
>>> print(len.__doc__)
Return the number of items in a container.
>>> print(ord.__doc__)
Return the Unicode code point for a one-character string.
>>> print(bin.__doc__)
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
>>> print(print.__doc__)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
You can also get information a function by calling the
help
function on it in an interactive session.
Simple if
An if
requires
a predicate, which is a boolean-valued expression. If the predicate
evaluates to True
, the CODE
executes. Otherwise
CODE
gets skipped.
if predicate:
CODE
This absolute value function has a simple if in it.
def f(x):
if x < 0: #simple if
x = -x
return x
def pass_NJ_license(score):
if score >= 80:
return "PASS"
else:
return "FAIL"
x = input("Enter a score: ")
x = int(x)
print(f"Your result is {pass_NJ_license(x)}")
Fork it: if/else
The if-else
progression looks like this. If the predicate evaluates
to True
the block TRUE_CODE
executes.
Otherwise, the block FALSE_CODE
executes. Something
is guaranteed to happen. This is a two-tined fork.
if predicate:
TRUE_CODE
else:
FALSE_CODE
Having a good tine with if/else/elif
You can have as many tines as you want with this construct.
if predicate1:
CODE_1
elif predicate2:
CODE_2
.
.
.
elif predicateN:
CODE_N
else:
CODE_DEFAULT