Python/ThreePartOperator

From ProgrammingExamples
< Python
Revision as of 14:30, 5 October 2011 by Griswolf (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Python does not supply the ?: operator, but it is sometimes very nice. Here's how to mimic it

We often want to set local variables to "what was passed, or if not, a default" like this:

def example(required, alist=None, anum=None, astring=''):
  my_list = alist or ['item']
  my_num = anum or 666
  my_string = astring or 'string'
  print('required: "%s"\nlist: %s\nNumber: %s\nString: "%s"'%(required, my_list,my_num,my_string))
 
example('must') # prints 'must' plus the three defaults
example('yes',anum=99) # prints 'yes', default, 99, default
# etc
.