0

I have a simple code below which adds the sum of 2 numbers together. However, I don't understand why the comma is able to print the result with a string datatype together with a float datatype. Does anyone know the explanation behind this concept of being able to add the string and float datatype together without conversion of the result variable?

Because, if the addition operator was to be used, I would have to convert the result variable from a float datatype to a string so that I can print the result with no errors. Thank you.

The code that adds the string and float datatypes together using ,:

firstnum = float(input("Enter the first number: "))
secnum = float(input("Enter the second number: "))
result = firstnum + secnum

print ("The sum of the two numbers is: ", result)

VS

The code that adds the string and float datatype using +:

firstnum = float(input("Enter the first number: "))
secnum = float(input("Enter the second number: "))

result = firstnum + secnum
convertedstring = str(result)

print ("The sum of the two numbers is: " + convertedstring)'''
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
bubbles
  • 9
  • 2
  • Does this answer your question? [Why can I not add an 'int' to 'str' in print function by using '+'?](https://stackoverflow.com/questions/64166090/why-can-i-not-add-an-int-to-str-in-print-function-by-using) – MisterMiyagi Feb 02 '22 at 14:13
  • Probably worth looking up `f-strings` while you're at it. – Chris Feb 02 '22 at 14:13

3 Answers3

1

That is because print can take multiple arguments and prints them separately with a space in between them. So there is no need for type conversion. In the latter case you are combining the two arguments into one, which does require type conversion.

The first print is basically the same as:

print("The sum of the two numbers is: ", end=" ")
print(result)

There are other (cleaner) ways to print this type of data where you don't need type conversion, for example with f-strings.

1

In the first case you're passing multiple arguments to the print function that will take care of printing all of them

In the second case you're evaluating an expression (that is a concatenation of strings) and you're passing only the value of this operation to the print function. Please note that on the second example you're not summing a string and a float but you're concatenating two strings using the + operator (and that's why you added the line convertedstring = str(result) to your code)

DaSim
  • 363
  • 5
  • 10
0

print function accepts any object or list of objects and always calls __str__ before writing to std so

print ("The sum of the two numbers is: ", result)

will call __str__ both for string and result and then print them separated by space on the other hand

print ("The sum of the two numbers is: " + convertedstring)

will first try to sum str and int, which will cause the TypeError exception.

sudden_appearance
  • 1,968
  • 1
  • 4
  • 15