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

Viewed 97000
def isBig(x):
   if x > 4: 
       return 'apple'
   else: 
       return 'orange'

This works:

if isBig(y): return isBig(y)

This does NOT work:

if fruit = isBig(y): return fruit

Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.

How to make it 1 liner, without calling the function twice?

7 Answers

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
Related