[Tutor] use of assignment expression

Alan Gauld alan.gauld at yahoo.co.uk
Sun Aug 16 18:31:02 EDT 2020


On 16/08/2020 14:55, Manprit Singh wrote:

> # Program to find smallest n digit number divisible by a number x
> n = 5
> x = 83
> if (no := (10**(n-1) % x)) == 0:
>     print(10**(n-1))
> else:
>     print((mx := (10**(n-1) + x)) - (mx % x))
> 
> The answer is 10043, which is the right answer . Just need to know if the
> way of using the assignment expression (2 times in the above example is
> efficient or not.),

Efficiency is not really the issue.
There are a few marginal cases where inline assignment is convenient
(and your else print expression is an example) but in most cases you
are simply trading a small amount of space saving with a significant
hit in readability and debuggability (is that a word?).

Even in the else expression any improvement in efficiency is not
likely to be high enough to sacrifice readability. Consider the alternative:

mx = 10**(n-1) + x
print( mx - (mx % x))

Is that one extra line really going to hurt so much?

> What i feel is the usage of assignment expressions is reducing the
> readability of the code written above  . Need your guidance.

I would agree. And it makes it much harder to debug since you
cannot examine the value before executing the if statement.

Just because a feature exists doesn't mean it's a good idea to
use it. Use it where there is a significant advantage. Readability
and testability should always come before efficiency and
especially before saving a few characters of typing.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list