Python function syntax

Most of python syntax is pretty simple and straight forward, but I sometime confused with the function definition one. Here is a reminder to my self:

  • kind: regular input parameter
  • *arguments: all the other input parameter except keyword arguments
  • **keywrods: the keyword argument, which must be at the last. Keyword argument is in the form of key='value'

Example:

def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments:
        print arg
    print "-" * 40
    keys = sorted(keywords.keys())
    for kw in keys:
        print kw, ":", keywords[kw]
        
cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")

produces:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

Comments

blog comments powered by Disqus