[Tutor] Use case of assignment expression
dn
PyTutor at DancesWithMice.info
Wed Apr 28 05:27:11 EDT 2021
[earlier copy sent to OP but missed the list - apologies]
On 28/04/2021 15.12, Manprit Singh wrote:
> Dear sir ,
>
> Consider an example to find the words from a given sentence having given
> word as prefix, program should return -1 if no such words found in the
> sentence.
>
> The code is written below :
>
> def word_found(string, wd):
> if word := [ele for ele in string.split() if ele.startswith(wd)]:
> return word
> else:
> return -1
>
> st = "Anuj is a good boy"
> wd = "goo"
> ans = word_found(st, wd)
> print(ans) returns ['good'] that is correct
>
> st = "Anuj is a bad boy"
> wd = "goo"
> ans = word_found(st, wd)
> print(ans) returns -1 that is also correct.
>
> My question is regarding assignment expressions used in function
> definition. Is this the appropriate use of assignment expression?
It works!
If the version of Python in-use supports assignment-expressions, what
concerns do you have?
(that it is being used inside a function?)
Ideas and discussion at https://www.python.org/dev/peps/pep-0572/
What is of-concern is that the problem has been formulated in an
old-fashioned manner - and possibly for use with other languages. "Clean
code" principles describe returning a single value which has multiple
meanings as a 'bad smell' (even though it is done all-the-time).
[a re-statement of @Dennis' point]
Python offers (at least) two further alternatives which may not have
been possible in the past/in some other language:
- return two values: one indicating found/not (likely a boolean), and
the other the word-list
- use raise and try...except to handle the not-found scenario
--
Regards,
=dn
More information about the Tutor
mailing list