开发者

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

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???


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;


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

money= int( float(money)-float(portfolio) )


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.


I think the problem here is assuming that because you have initialised variables with integer values they will remain as integers. Python doesn't work this way. Assigning a value with = only binds the name to the value without paying any attention to type. For example:

a = 1       # a is an int
a = "Spam!" # a is now a str

I assume yahoostock.getprice(), like many functions that get data from websites, returns a string. You need to convert this using int() before doing your maths.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜