Arguments are passed by assigning local names to objects.
Strings and numbers are immutable objects. They cannot be changed from the function. Lists and dictionaries are mutable and can be changed.
#!/usr/bin/env python def func( a, b): a = 1 # has only a local effect b[0] = 2 # changes the list in the calling function return c = 3 d = [4, 5] func( c, d) print( " c ", c) print( " d ", d)
Arguments may be collected in a list:
def scanFunc( *a): print( a) return scanFunc( 1, 2, 3)
#!/usr/bin/env python def func( a, b, c): print( a, b, c) return a = [1, 2, 3] func( *a)
Arguments may be collected in a dictionary:
#!/usr/bin/env python def scanFunc( **a): print( a) return scanFunc( start = 0, stop = 10, delta = 1)
Functions can have default values for arguments:
def yes_or_no(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print( complaint) print( yes_or_no( "do you really want it "))
Here are examples for keyword arguments:
def scan( start, stop=100, delta=1): print( "scan from ", start, " to ", stop, "by ", delta) scan( 10) # -> scan from 10 to 100 by 1 scan( 10, 200, 5) # -> scan from 10 to 200 by 5 scan( 10, 200, delta=5) # -> scan from 10 to 200 by 5 scan( 10, stop=200, delta=5) # -> scan from 10 to 200 by 5
Receiving a list:
def func( *a): print( a) func( 'a', 2, 3)
Receiving a dictionary:
def func( **a): print( a) func( start= 0, stop= 10)
Collecting a list and a dictionary:
def scan( fname, *lst, **dct): print( fname, lst, dct) scan( 'tst.fio', '1st comment', '2nd comment', start=0, stop=10, delta=1)
range() receives an unpacked list.
In [4]: a = [0,10] In [5]: range(*a) Out[5]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
func() receives an unpacked dictionary.
def func( name, start=0, stop=10): print( name, start, stop) dct = {'name': 'tst', 'start': 1, 'stop': 2} func( **dct)