-2

I am trying to write a program whereby the user can enter two values, and the program will calculate the absolute error between the values.

A sample input would be:

87.03

87

With the approximate value read in first and the correct value second. The output should be:

The absolute error is: 0.03

Here is my attempt that is refusing to work!

a=raw_input("What is the approximate value?")

b=raw_input("What is the correct value?")

print "The absolute error is: %s" %abs(a-b)

The error I'm getting is:

TypeError                                           
Traceback (most recent call last)

<ipython-input-1-9320453c4e23> in <module>()

  1 a=raw_input("What is the approximate value?")

  2 b=raw_input("What is the correct value?")

----> 3 print "The absolute error is: %s" %abs(a-b)


TypeError: unsupported operand type(s) for -: 'str' and 'str'

And I really do not have any idea what it means. Any help would be greatly appreciated.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
PythonNoob
  • 1
  • 1
  • 1

2 Answers2

1
a = float(raw_input("What is the approximate value?"))

b = float(raw_input("What is the correct value?"))

You need to make the input into floats

raw_input("What is the approximate value?") without casting to float is a string.

In [8]: b = "0.85"

In [9]: a = "10.5"

In [10]: a-b
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-12776d70544b> in <module>()
----> 1 a-b

TypeError: unsupported operand type(s) for -: 'str' and 'str'

In [11]: a = float("10.5")

In [12]: b = float("0.85")

In [13]: a-b
Out[13]: 9.65
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

raw_input will take an input string from the user and keep it as a string. So you're trying to do a-b when a and b are both strings. Convert them to floats first using float().

a = float(raw_input("What is the approximate value?"))
b = float(raw_input("What is the correct value?"))
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42