-2

I have been working on a pythagorus theorem calculator on python Here is my code so far:

a = int(raw_input("what is length a?"))
b = int(raw_input("what is length b?"))
a2 = a*a 
b2 = b*b 
c2 = a2+b2
c = c2**0.5
print "the length of c is " + c

It will not work on the last line. It throws the following error:

cannot concatenate 'str' and 'float' objects

Does anyone know what's wrong with it?

Michelle
  • 2,830
  • 26
  • 33
user3617742
  • 37
  • 1
  • 4
  • 2
    Exactly what the error says - it can't put a string ("the length of c is") and a float (`c`) together. You need to tell it to treat the number as a string by casting it. – Michelle May 27 '14 at 16:40
  • Try google next time. I got about 50 results when i googled "cannot concatenate 'str' and 'float' objects" – Elias May 27 '14 at 16:57

3 Answers3

1

Just what it says: c is a float, but "the length of c is " is a string. As a quick fix you can do this: "the length of c is " + str(c), but you will want to learn about string formatting.

Tom
  • 22,301
  • 5
  • 63
  • 96
  • Thank you, I have tried this and it works well. If "the length of c is " is the string, why is it not str("the length of c is ") + c? – user3617742 May 27 '14 at 16:49
  • because `"the length of c is "` is already a string, it does not need to be cast to a string type with `str()`, it is not the problem. The problem is the `c` variable; it is not of the type `string`, and therefore does not have the class attributes that are inherent to strings (like concatenation in this case). In your scope, `c` is of type `int`, so we must cast it to a string before we can treat it as such. Think of it this way, `c` being an integer can not be concatenated in the same way as you cant set its value to upper case, who ever heard of upper case '45'? – MikeRixWolfe May 27 '14 at 17:10
0

c is an int, "the length of c is " is a string

You would have to say

print "the length of c is ", str(c)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

Try print "the length of c is %.3f" % (c,)

Concatenation is combining strings together, and Python doesn't automatically convert non-strings to strings (unlike Java).

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40