[Level 2] iif in Python
If you want to implement iif in Python,
please refer to the following sample code:
Because the prededence of string concatenation is higher than if.
Therefore you need to use () to make it correct.
regards,
Stanley Huang
please refer to the following sample code:
#!/bin/env python def iif(b): return 'It\'s True' if b else 'It\'s False' print iif(True) print iif(False)And the following sample, guess what will you get!
#!/bin/env python b = True print 'b: %s' % 'Ture' if b else 'False' b = False print 'b: %s' % 'Ture' if b else 'False'Result:
$ ./iif.py b: Ture FalseThe second result is "False", not "b: False". Why???
Because the prededence of string concatenation is higher than if.
Therefore you need to use () to make it correct.
#!/bin/env python b = True print 'b: %s' % 'Ture' if b else 'False' b = False print 'b: %s' % ('Ture' if b else 'False')Wish this helps.
regards,
Stanley Huang
Comments
Post a Comment