简体   繁体   English

为什么我的股价在一定范围内的测试不起作用?

[英]Why doesn't my test that a share price is in a certain range work?

I have a little code that doesn't work; 我有一些无效的代码;

yahoo = Share('YHOO')
a = yahoo.get_price() #get price of stock
print "ok" if 45 <= a <= 50 else "no"

It is always printing "no" even when the stock price is 45.55 即使股价为45.55,也始终打印“否”

Assuming that you're using yahoo-finance (in which case, it would have been helpful to say so in your question), Share.get_price() returns a string : 假设您使用的是yahoo-finance (在这种情况下,在您的问题中这样说会很有帮助), Share.get_price() 返回一个字符串

 >>> from yahoo_finance import Share >>> yahoo = Share('YHOO') >>> print yahoo.get_open() '36.60' >>> print yahoo.get_price() '36.84' 

So, you'll have to convert it to a Decimal object before doing any math or numeric comparison with it: 因此,您必须先对其进行数学或数字比较,然后将其转换为Decimal对象:

from decimal import Decimal

yahoo = Share('YHOO')
a = Decimal(yahoo.get_price())
print "ok" if 45 <= a <= 50 else "no"

Decimal is preferable to float if you're dealing with currency information, to avoid rounding errors . 如果要处理货币信息,最好使用Decimal不是float ,以避免舍入错误

it may be the case that you get a string instead of a number 可能是您得到的是字符串而不是数字

>>> a=45.55   #float
>>> 45 <= a <= 50
True
>>> a="45.55"  #string
>>> 45 <= a <= 50
False
>>> 

to know the type do 知道类型吗

>>> type("45.55")
<type 'str'>
>>> type(45.55)
<type 'float'>
>>> 

for your code to work properly you need to get one of the numeric types int , long or float for the build-in, (also Fraction and Decimal build-in too, but you need to import them) 为了使代码正常工作,您需要获取内置的数字类型intlongfloat (也可以是FractionDecimal内置,但您需要导入它们)

to fix your code just cast it to the correct numeric type like float or Decimal 要修复您的代码,只需将其转换为正确的数字类型,例如floatDecimal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM