Loonhaunt
Loonhaunt

Reputation: 21

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

This is so simple that none of the messages that I have found so far deal with my low level problem but here is my code.

name=input("What is your name?")
weight=input("How much do you weigh?")
target=input("What would you like to weigh?")
loss=weight-target
print("So...",name,'You need to lose',loss,"pounds!")
print("\n\nPress enter key to scram!")

The error:

Traceback (most recent call last):
  File "/Users/davebrown/Desktop/Pract.py", line 7, in <module>
    loss=weight-target
TypeError: unsupported operand type(s) for -: 'str' and 'str'

I don't understand why is it unsupported?

Upvotes: 2

Views: 2838

Answers (3)

alexis
alexis

Reputation: 50180

You are apparently using python 3. The result of input is always a string, so you must convert them to integers before you can do arithmetic. (In python 2, input will interpret what you type in as python code, so your code would have worked as intended).

weight=int(input("How much do you weigh? "))

etc.

You can "add" strings together with +, but there's no corresponding subtraction operation. And if there was, given the way string "addition" works, subtracting "25" - "5" would have given you "2"! So you you must convert to integers to get the intended result (a corresponding program about gaining weight would not have triggered a python error, but would have given very worrisome results).

Upvotes: 0

Deelaka
Deelaka

Reputation: 13693

You need to convert the strings to integers first which can be done using the built-in int() or float() functions

So Try this instead:

weight= int(input("How much do you weigh?"))
target= int(input("What would you like to weigh?"))

Note:

In python, You cannot perform mathematical functions such as division or subtraction on a string without converting it to a integer first However string addition and multiplication can be performed, However for your case neither string addition or multiplication will work

Example:

>>> 'Hi' + ' Bye!'
'Hi Bye!'
>>> 'Hi' * 5
'HiHiHiHiHi'

Upvotes: 2

falsetru
falsetru

Reputation: 368894

You cannot substract str object. (input in Python 3.x returns str object unlike input in Python 2.x)

>>> '2' - '1'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Convert them into int or float first.

>>> int('2') - int('1')
1

Upvotes: 5

Related Questions