Difference between revisions of "Python/ThreePartOperator"

From ProgrammingExamples
Jump to: navigation, search
m (better example using a False default: It still works)
m (minor correction)
 
Line 9: Line 9:
 
   print('required: "%s"\nlist: %s\nNumber: %s\nString: "%s"'%(required, my_list,my_num,my_string))
 
   print('required: "%s"\nlist: %s\nNumber: %s\nString: "%s"'%(required, my_list,my_num,my_string))
 
</syntaxhighlight>
 
</syntaxhighlight>
Since version 2.5, however, Python has an official  [http://docs.python.org/reference/expressions.html#conditional-expressions ternary operator] called a "conditional operator": <code>x if C else y</code> evaluates C first, then either x or y.
+
Since version 2.5, however, Python has an official  [http://docs.python.org/reference/expressions.html#conditional-expressions ternary operator] called a "conditional expression": <code>x if C else y</code> evaluates C first, then either x or y.

Latest revision as of 14:55, 5 October 2011

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.