-1

I want to print out the sum of str and float number by using the type function but somehow it's not working

var1,var2,var3=[str(2),float(3.0),str(5)]
print([var1,var2,var3])

if I simply apply plus function print(var1+var2+var3) it gives an error which I don't understand

TypeError: must be str, not float

Abdullah Ahmed Ghaznavi
  • 1,978
  • 3
  • 17
  • 27

1 Answers1

1

You need to write:

print(sum(float(i) for i in [var1,var2,var3]))

But instead you can easily use it as below:

values = [str(2),float(3.0),str(5)]

in case the types are not matching you need to convert it to same type and then add it so you can do in one line by list comprehension as below:

float_values = [float(i) for i in values]  # list of all values as float
print(sum(float_values))

+ operator

when you use strings with + operator it will concatenate strings

Ex.

x = '4' + '5'  # result will be '45'

If you use it for integer it will give you addition of values Ex.

x = 4 + 5  # result will be 9
Gahan
  • 4,075
  • 4
  • 24
  • 44