[Tutor] Re: explicit return functions

Charlie Clark Charlie@begeistert.org
Tue, 30 Oct 2001 16:58:26 +0100


>> What's the rule about using a explicit return command in  
>> functions?  
> 
>return returns values - which may be None... 
> 
>> works the same as: 
>>  
>> def printSquare(number): 
>>     print number**2 
>>  
>> What's preferred? 
> 
>Personally I prefer the second case shown above. If  
>there's nothing to return don't use return... 
> 
I think, but I may well be wrong, that the difference is more than mere 
preference. Using "return" and "print" in the Pyhton interpreter will 
always seem to do the same thing but that isn't the case inside 
programs. If you want to *see* the result of a function you should just 
print it. If you want to *use* the result of a function, return it.

def PrintSquare(x):
	print x**2

def ReturnSquare(x):
	return x**2

now try this:
PrintSquare(3)
>>> 9
ReturnSquare(3)
>>> 9

but try
result =  PrintSquare(3)
>>> 9
print result
			# prints nothing as result has not been assigned a value
result = ReturnSquare(3)
>>>
print result 
9

Returning the value allows to do something with it.

Charlie