Consider carefully what you want each function to do. Arbitrarily inserting return values is counterproductive. If a function is meant to return the result of a computation, then let its return be just that, and nothing else.
Under that premise this question would never have come up, although it is good that it did, and now we know.
Treat functions like mathematical equations.
f(x) = some function of x
y = f(some x)
Make them simple and always have a return so the expression they are used in makes sense and evaluates correctly. Don’t write programs inside a function. Write pure, concise algorithms that always have predictable results that are consistent across all inputs.
def mul(a, b):
return a * b
y = mul(m, n) + o
Done and dusted.
The place to write a program is inside an object, namely a class. It may end up involving several class defined objects, but it is still a class. This form of composing code refines the method library so that they are all associated to a particular (one or other) class, not just functions out in the open namespace. Methods are expected to recognize their respective objects and know how to access their attributes. Functions aren’t that intelligent. They don’t know what we give them unless we tell them.
For example, let’s take multiplication, to continue from above. Python
int instances have a
__mul__ attribute. When the program sees us multiply two integers, it treats the first as self, and the second as other.
return self.value * other.value
It was the
__mul__() method that performed that operation.
>>> a = 6
>>> b = 7
That’s the progression when Python sees this…
a * b
Remember, built-ins act upon any object; methods act only upon instance objects.
Multiplication is a method, not a function.
The repeat operator
Python has extended the meaning of
* in that if the types don’t match, and the opposing type is a character it will repeat their value N times (N being the number in the expression).
>>> 'O' * 8
>>> ['O'] * 8
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
>>> [['O' * 8] * 8]
['OOOOOOOO', 'OOOOOOOO', 'OOOOOOOO', 'OOOOOOOO', 'OOOOOOOO', 'OOOOOOOO', 'OOOOOOOO', 'OOOOOOOO']
Note that in the second example we introduced a list as the containing data structure.
Definitely play with this operator in the sandbox. Learn its behavior. Time well spent, imho.