Why x+=1 doesn't return x value instead of an object

dn PythonList at DancesWithMice.info
Sat Oct 31 01:42:54 EDT 2020


On 31/10/2020 16:20, Chris Angelico wrote:
> On Sat, Oct 31, 2020 at 1:51 PM Jon Ribbens via Python-list
> <python-list at python.org> wrote:
>>
>> On 2020-10-31, Stefan Ram <ram at zedat.fu-berlin.de> wrote:
>>> Siddhharth Choudhary <siddharth654choudhary at gmail.com> writes:
>>>> I want to know why x+=1 does not return the value of the variable.
>>>
>>>    Which value? The old or the new one?
>>>
>>>    Expressions never return values.
>>
>> Except when they're assignment expressions, when they do.
> 
> Expressions DO have values, but assignment is a statement, not an
> expression. (Assignment expressions don't have augmented forms, so
> there's no ambiguity.)


So, you've already realised that:

 >>> x = 1
 >>> print( x += 2 )
   File "<stdin>", line 1
     print( x += 2 )

isn't going to work.

However it is possible to achieve something of what you ask (Python 
3.8+), using the 'walrus operator' in/as an assignment-expression:

 >>> x = 1
 >>> print( x := x + 2 )
3

but as others have said, an augmented-expression is not a "named 
expression". Accordingly, the more usual walrus application will be 
something like:

 >>> if ( x := 1 + 2 ) > 1.5:
...     print( f"Yes! { x }" )
... else:
...     print( f"No! { x } <= 1.5" )
...
Yes! 3


Documented in the manual at 
https://docs.python.org/3/reference/expressions.html?highlight=walrus#assignment-expressions

Read more at https://www.python.org/dev/peps/pep-0572/


Free advice: whatever you do, don't call @Chris a walrus!
-- 
Regards =dn


More information about the Python-list mailing list