Difference between revisions of "Python/ThreePartOperator"
From ProgrammingExamples
< Python
(rewrite to mention conditional operator) |
m (better example using a False default: It still works) |
||
Line 5: | Line 5: | ||
def example(required, alist=None, anum=None, astring=''): | def example(required, alist=None, anum=None, astring=''): | ||
my_list = alist or ['item'] | my_list = alist or ['item'] | ||
− | my_num = anum or | + | my_num = anum or 0 # note that 0 evaluates False, but is still chosen here |
my_string = astring or 'string' | my_string = astring or 'string' | ||
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 operator": <code>x if C else y</code> evaluates C first, then either x or y. |
Revision as of 14:53, 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 operator": x if C else y
evaluates C first, then either x or y.