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

前端 未结 8 1337
野趣味
野趣味 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:48

    The problem is that the assignment operation cannot be evaluated as having a boolean value. The if statement relies on being able to evaluate a boolean. For example,

    >>> fruit = 'apple'
    >>> bool(fruit = 'apple')
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    
    /Users/jem/ in ()
    
    TypeError: 'fruit' is an invalid keyword argument for this function
    >>> bool('a')
    True
    

提交回复
热议问题