Input value: 6+5
Example: Within the variable data
are the numbers ['6', '5']
,
print (data).split('+')
How do I print the sum of these values?
Input value: 6+5
Example: Within the variable data
are the numbers ['6', '5']
,
print (data).split('+')
How do I print the sum of these values?
Use sum
:
data = ['6', '5']
print (sum(int(numero) for numero in data if numero.isdigit())) # 11
Considering that you will always receive either numeric or mathematical operations.
First you will separate the data of the string that arrives for you:
>>> string = "6+5".split("+")
>>> string
['6','5']
Then you have to convert them into numbers treatable by python functions, so use int
or float
. I will use the map
function to perform an operation for each element in the list.
>>> operadores = list( map(float,string) )
>>> operadores
[6.0 , 5.0]
>>> soma = sum(operadores)
11.0
Or using fewer variables:
soma = sum ( list ( map ( float,data ) ) )