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

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

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (isBig(y)) as a variable (x) in order to re-use it within the body of the condition:

    if x := isBig(y): return x
    

提交回复
热议问题