The "aesthetic" is very relative, and in general it is preferable to evaluate other elements such as performance, maintainability, security or readability before the code looks nice. Having said that, let's look at some possibilities:
The traditional way of defining a function that receives two parameters. If the requirement is that you must add two numeric values, this is the appropriate way to define a function:
def sumar(valor1, valor2):
return valor1 + valor2
print(sumar(1,2))
Eventually we could redesign the function to accept more than one value by using variable parameters:
def sumar1(*valores):
return sum([v for v in valores])
print(sumar1(1,2))
print(sumar1(1,2,3,4))
In this example, [v for v in valores]
is a technique called "list comprehension", basically: "create a list for each element of the iterable valores
" . Finally we apply sum()
to the list.
This other option may be the answer to your question, the idea is to pass 2 or more values separated by +
, clearly to do this, we must pass a string, let's see:
def sumar2(valores):
return sum([int(v) for v in valores.split("+")])
print(sumar2("1+3+4"))
It is not uncommon to have to do this, many times we will receive "strings" of characters from other programs, APIs, interfaces, etc. and we will have to do something like this. First we "separate" the values by the +
character using split()
, which is an own method of any chain, with the same we will obtain a set of characters that represent numbers, to each of these values we convert it to integer by means of int()
and we transform it into a list by" understanding lists ", finally we apply the function sum()
that adds up the entire list.
And finally and only as anecdotal data since we should not use it unless we have absolute security about the input. We have eval()
which allows you to evaluate a Python string, in the example, we return the evaluation of "1 + 3 + 4".
def sumar3(valores):
return eval(valores)
print(sumar3("1+3+4"))
It is a very flexible way because we could evaluate different things like 1/2 * 3^2
or also dangerous as sumar("__import__('os').system('ls .')")
.
I hope it's useful for you.