Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

a'$'

money=1000000;
portfolio=0;
value=0;
value=(yahoostock.get_price('RIL.BO'));
portfolio=(16*(value));
print id(portfolio);
print id(value);
money= (money-portfolio);
'''

I am getting the error:

Traceback (most recent call last):
  File "/home/dee/dee.py", line 12, in <module>
    money= (value-portfolio);
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Since money is integer and so is portfolio, I cant solve this problem..anyone can help???

like image 587
user979204 Avatar asked Oct 04 '11 20:10

user979204


3 Answers

value=(yahoostock.get_price('RIL.BO'));

Apparently returns a string not a number. Convert it to a number:

value=int(yahoostock.get_price('RIL.BO'));

Also the signal-to-noise ratio isn't very high. You've lots of (,), and ; you don't need. You assign variable only to replace them on the next line. You can make your code nicer like so:

money = 1000000
value = int(yahoostock.get_price('RIL.BO'));
portfolio = 16 * value;
print id(portfolio);
print id(value);
money -= portfolio;
like image 185
Winston Ewert Avatar answered Nov 20 '22 23:11

Winston Ewert


money and portfolio are apparently strings, so cast them to ints:

money= int( float(money)-float(portfolio) )
like image 38
Chriszuma Avatar answered Nov 20 '22 22:11

Chriszuma


As the error message clearly states, both are string, cast with int(var).

Note:

Let's see what can we decude from the error message:

portfolio must be string(str), which means value is also a string. Like this:

>>> 16*"a"
'aaaaaaaaaaaaaaaa'

and apparently you missed to post relevant code because the error message tells you that money is str as well.

like image 2
Karoly Horvath Avatar answered Nov 20 '22 21:11

Karoly Horvath