Difference between revisions of "Python/ThreePartOperator"
From ProgrammingExamples
< Python
m |
(rewrite to mention conditional operator) |
||
Line 1: | Line 1: | ||
− | Python | + | 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 <code>False</code> you can use the <code>or</code> operator which takes the leftmost operand that evaluates to <code>True</code> or the right operand if neither evaluates <code>True</code>. Like this: | |
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
def example(required, alist=None, anum=None, astring=''): | def example(required, alist=None, anum=None, astring=''): | ||
Line 8: | Line 8: | ||
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. | |
− | + | ||
− | + |
Revision as of 14:52, 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 666 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.