Function returns – Python

Truth, or not

Defined functions in Python will always return something, even if you don’t specifically return something. If nothing is returned, Python will actually return a value of ‘None’ which is still something. To illustrate this I’ll create a very simple function:

def test(x):
	pass

I’ll create a string and then pass it through the function and do an action based on the return value.

if test(a) is True:
	print(a,"is True")
else:
	print(a,"is not True")

	
string is not True

Python has a few handy shortcuts. Instead of evaluating if test(a) is True, I can simply say if test(a):

if test(a):
	print(a,"is True")
else:
	print(a,"is not True")

	
string is not True

If I return nothing in a function, ‘None’ is actually returned. Any 0 value, False, or None are all returned as non-true values. Let’s test a few return values and see what we get:

def test(x):
	return 1
if test(a):
	print(a,"is True")
else:
	print(a,"is not True")

	
string is True

def test(x):
	return -1
if test(a):
	print(a,"is True")
else:
	print(a,"is not True")

	
string is True

I can also implicitly return False values. The following three all have the same result:

def test(x):
	return 0

def test(x):
	return False

def test(x):
	return None
if test(a):
	print(a,"is True")
else:
	print(a,"is not True")

	
string is not True

Note that True, False, None, etc, are keywords and have their first letter capitalised.

Multiple returns

How are multiple values returned from a defined function? Let's check:

def test():
	a = 1
	b = 2
	c = 3
	return a,b,c
y = test()
type(y)
<class 'tuple'>

I'm simply calling the function. When a defined function returns multiple values, those values are returned in a tuple. As before, if any value is a false value we could use that later:

def test():
	a = 1
	b = 2
	c = 0
	return a,b,c
y = test()
>>> for i in y:
	if i:
	    print(i)
		
1
2

The value returned by c is not printed as its not True.

What goes in...

The parameters of a defined function does not have to match the argument we pass into it. The return value also doesn't have to match it:

def say_hello(x):
	a = "Hello "+x
	return a
print(say_hello("Darren"))
Hello Darren

Here I have passed in the string "Darren" as argument 'x'. The function creates a new variable 'a' which concatenates the string "Hello" with string "Darren" passed in. The value returned is the concatenation.
Another important thing to note here is that 'a' returns a value, 'a' itself is not returned. 'a' does not have scope outside the function:

a
Traceback (most recent call last):
  File "<pyshell#109>", line 1, in <module>
    a
NameError: name 'a' is not defined

I could create a global variable that takes the value of the output of the function:

 b = say_hello("Darren")
b
'Hello Darren'

© 2009-2020 Darren O'Connor All Rights Reserved -- Copyright notice by Blog Copyright