returning totals in functions of math
On 09/11/2020 08:14, 2QdxY4RzWzUUiLuE at potatochowder.com wrote:
> On 2020-11-08 at 19:00:34 +0000,
> Peter Pearson <pkpearson at nowhere.invalid> wrote:
>> On Sun, 8 Nov 2020 13:50:19 -0500, Quentin Bock <qberz2005 at gmail.com> wrote:
>>> Errors say that add takes 1 positional argument but 3 were given? Does this
>>> limit how many numbers I can have or do I need other variables?
>>> Here is what I have:
>>> def add(numbers):
>>> total = 1
>>> for x in numbers:
>>> total += x
>>> return total
>>> print(add(1999, -672, 84))
>> Your function "add" expects a single argument that is a list
>> of numbers. You're passing it three arguments, each a number.
>> Try add([1999, -672, 84]).
Minor point ('here'): aren't arguments passed as a tuple? (cf "list")
[next point probably more advanced than OP requires]
Major 'gotchas' elsewhere: remember the difference between passing an
immutable, cf a mutable, argument (tuple cf list)! Also related,
>>> my_list = [ 1, 2, 3 ]
>>> def function1( any_list ):
... any_list = [ 4, 5, 6 ]
>>> function1( my_list )
[1, 2, 3]
>>> def function2( any_list ):
... any_list.append( [ 4, 5, 6 ] )
>>> function2( my_list )
[1, 2, 3, [4, 5, 6]]
- neither of which works with tuples...
Some refer to such mutable 'flexibility' as a "side-effect" and thus
undesirable/to be avoided.
> Or change add to accept an arbitrary number of arguments and collect
> them into a tuple:
> def add(*numbers):
> # then the rest of the function as before
> BTW, why initialize total to 1?
Because OP copied 'multiply' code, completed earlier?
Once you have this code working, as above, consider refactoring to use