How to assign a variable in an IF condition, and then return it?

前端 未结 8 1347
野趣味
野趣味 2020-11-27 06:05
def isBig(x):
   if x > 4: 
       return \'apple\'
   else: 
       return \'orange\'

This works:

if isBig(y): return isBig(y)
         


        
8条回答
  •  长情又很酷
    2020-11-27 06:42

    The one liner doesn't work because, in Python, assignment (fruit = isBig(y)) is a statement, not an expression. In C, C++, Perl, and countless other languages it is an expression, and you can put it in an if or a while or whatever you like, but not in Python, because the creators of Python thought that this was too easily misused (or abused) to write "clever" code (like you're trying to).

    Also, your example is rather silly. isBig() will always evaluate to true, since the only string that's false is the empty string (""), so your if statement is useless in this case. I assume that's just a simplification of what you're trying to do. Just do this:

    tmp = isBig(y)
    if tmp: return tmp
    

    Is it really that much worse?

提交回复
热议问题