[Tutor] Testing print
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Oct 1 20:19:09 EDT 2016
On 01/10/16 23:08, boB Stepp wrote:
> On Sat, Oct 1, 2016 at 11:35 AM, Alan Gauld via Tutor <tutor at python.org> wrote:
>
>> ... Personally I don't like functions that
>> sometimes return one and sometimes two results. I'd rather
>> you returned a None first argument in the first case
>> to make it consistent.
>
> Why don't you like doing this? What are the pluses and minuses as you
> see them?
Because client code has to guess which return value is relevant
consider
def f(x):
if x%2: # is odd
return x,x+1
else: return x
Now I want to use f on a collection of integers:
nums = [1,2,3,4]
for n in nums:
result = f(n)
if result <= 3: # broken for 1 and 3
print("success")
else: ....
But if I change it to
for n in nums:
result = f(n)
if result[0] <= 3: # now broken for 2 and 4
print("success")
else: ....
So I need to introduce code to determine whether I got
an int or a tuple back and then separate code for each
case. If I know that the result is always an int I can
use the first case if I know its always a tuple I can
use the second. But not knowing which is just plain
messy.
--
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