Class 23 — October 16

Functional living

The task before us — Turn the abstract to concreted – Functions are at hand


Look both ways


Agenda


Druthers



Why have functions


Function definition syntax and terminology

def function-name( parameters ) :

  ''' header-comment '''

  action

The keyword def signals that a function is being defined.

The function-name is an identifier that names the task.

The ( parameters ) are a list of variable names (identifiers). The values of the parameters are the values needed by the function upon start up. The function-name along with the parameters form the function header.

The colon ( : ) is a separator of the function header from the function statement block.

Although optional, the literal string ''' header-comment ''' is normally the first line following the function header. The header-comment is a documentation string or as it commonly abbreviated docstring. The header-comment docstring describes the operation of the function. A Python installation comes with tools (e.g., Sphinx) for automatically generating online documentation from a program's triple-quoted strings. Comments intended for online documentation are written as docstrings.

The action is the block of statements to be executed when the function is called upon. The statements can include a return statement(s) that specifies the value to be associated with the function's usage. Note, return is a keyword.


Function invocation syntax and terminology

module-name . function-name ( arguments )

import url

reply = input( 'Enter web file: ' )

link = reply.strip()

text = url.get_contents( link )


Function invocation semantics — what happens under the hood

s = "Cole's law: marinate shredded cabbage in vinaigrette."

x = print( s )

print( x )

indicates even the print() function returns a return. The snippet output is

Cole's law: marinate shredded cabbage in vinaigrette.

None



Staying within the law of scope

import url

page = url.get_contents( 'http://www.cs.virginia.edu/~cs1112/' )

print( url.get_contents.bytes )


What's next


To do