Python/ThreePartOperator

From ProgrammingExamples
Jump to: navigation, search

Early versions of Python did not supply a "ternary operator", but it is sometimes very nice.

If you simply want a default value in case the initial value evaluates to False you can use the or operator which takes the leftmost operand that evaluates to True or the right operand if neither evaluates True. Like this:

def example(required, alist=None, anum=None, astring=''):
  my_list = alist or ['item']
  my_num = anum or 0 # note that 0 evaluates False, but is still chosen here
  my_string = astring or 'string'
  print('required: "%s"\nlist: %s\nNumber: %s\nString: "%s"'%(required, my_list,my_num,my_string))

Since version 2.5, however, Python has an official ternary operator called a "conditional expression": x if C else y evaluates C first, then either x or y.