Functions

From Training Material
Jump to navigation Jump to search


Structuring code with functions

A function is an autonomous sub-program with local variables, input and output. In Python, a function definition must be followed by a code block:

def calc_price(fruit,n):
'''Returns the price of fruits.'''
if fruit=='banana':
return 0.75 * n

# call the function
print calc_price('banana',10)

Parameters

Function parameters may have default values. In that case, they become optional.

Do not use lists or dictionaries as default values!

def calc_price(fruit,n=1):


print calc_prices('banana')
print calc_prices('banana',100)

Return values

A function may return values to the program part that called it. More than one value is returned as a tuple. In any case, the return statement ends the functions execution.

return 'banana',0.75

Good style for writing functions

  • Each function should have one purpose only.
  • A clear name starting with a verb.
  • A documentation string (with triple quotes).
  • One return type or one modified input object.
  • Necessary parameters.
  • Optional parameters.
  • Do not use global variables in a function.
  • Keep functions small (<100 lines).