[Tutor] function return values

Phil phillor9 at gmail.com
Fri Dec 3 00:34:22 EST 2021


On 2/12/21 18:16, Cameron Simpson wrote:
>
> For a function returning a valid result or no result you have two main
> approaches in Python:
> - return the result or None (or None-ish, as you are doing)
> - return the result or raise a ValueError("no solution found")

Thank you Cameron for your detailed reply which has given me something 
to think about.

I think the return of None, None, None is the simplest option. My 
calling function was originally only testing for a list of two elements 
and ignoring the other two variables. I think this is still correct, an 
empty list or a list containing 1 element is not valid. I'll experiment 
further with this.

Alan has pointed out an error: I do not need to keep searching after a 
pair has been found but I do need to search beyond the first row. The 
pair could be on row 2 or 3.

I've seldom ever used exceptions and I've never found a case where I 
could use the yield statement. I can see that it would be useful if I 
needed to return multiple values of the same variable from a function. 
I'll try to keep the yield statement in mind it could be useful 
somewhere and better than the use of a list.

> or this for your None-ish approach:
>
>      item, row, column_list =_ self.boxPairsInSameRow(candidate_pairs, x , y)
>      if (item, row, column_list) == (None, None, None):

Should the Nones be enclosed within brackets? I didn't do that. I know 
that "if (a + b) == 2" is C syntax.


> A third alternative turns on your statement: "Once the pairs have been
> found on a row then there is no need to search the remaining row or
> rows". Is it _meaningful_ to search for more solutions, even if you
> _currently_ just want the first one?

There can only be a pair and they must be on the same row, not 
necessarily on the first row. So what I wrote was not correct. I do not 
need to continue searching once a pair has been found on a row but I do 
need to search beyond the first row in case the pair is on row 1 or 2. I 
don't think the use of a generator is called for here.

-- 

Regards,
Phil



More information about the Tutor mailing list