+ 1

Why is the result getting converted to str?

elif user_input == "add": num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = str(num1 + num2) print("The answer is " + result)

27th Jun 2017, 3:53 AM
Abhishek Hugar
Abhishek Hugar - avatar
2 ответов
+ 7
num1 = 1.2 num2 = 3.4 print( num1 +num2 ) # ok print("" + num1 + num2) # TypeError: Can't convert 'float' object to str implicitly. str(float_object) is EXPLICIT and Python is happy.
27th Jun 2017, 4:10 AM
Kirk Schafer
Kirk Schafer - avatar
+ 5
Removed my last comment to avoid any miss-understanding. If he/she wanted to print them together without having cast it to a string they could have separated it with a comma. print("my str", result) I suppose he/she tried the + and got an error so just converted it to avoid the error, even though the casting was not necessary
27th Jun 2017, 4:07 AM
Rrestoring faith
Rrestoring faith - avatar