python - 我怎样才能使这段代码更加Pythonic——具体来说,将一些东西合并到一个函数中?

标签 python python-3.x

我知道,如果我这样做的话,这段代码看起来会好很多,以便在一个函数中检查当前价格与开盘价,这样我就不必为我想检查的每只股票重新编写它,但我不知道如何开始正确地做到这一点。你们中有人有一些建议可以帮助我入门吗?

from yahoo_finance import Share

apple = Share('AAPL')

appleopen = float(apple.get_open())
applecurrent = float(apple.get_price())

if appleopen > applecurrent:
    print(("Apple is down for the day. Current price is"), applecurrent)
else:
    print(("Apple is up for the day! Current price is "), applecurrent)

applechange = (applecurrent - appleopen)
if applechange > 0:
    print(('The price moved'),abs(applechange),("to the upside today."))
else:
    print(('The priced moved'),abs(applechange),("to the downside today."))
print('-----------------------')
nflx = Share('NFLX')

nflxopen = float(nflx.get_open())
nflxcurrent = float(nflx.get_price())

if nflxopen > nflxcurrent:
    print(("Netflix is down for the day. Current price is"), nflxcurrent)
else:
    print(("Netflix is up for the day! Current price is "), nflxcurrent)

nflxchange = (nflxcurrent - nflxopen)
if nflxchange > 0:
    print(('The price moved'),abs(nflxchange),("to the upside today."))
else:
    print(('The priced moved'),abs(nflxchange),("to the downside today."))

最佳答案

试试这个:

from yahoo_finance import Share
Store = {
    'AAPL': 'Apple',
    'NFLX': 'Netflix'
}
for code in Store:
    name, shr = Store[code], Share(code)
    sopen = float( shr.get_open() )
    scurr = float( shr.get_price() )
    schange = scurr - sopen
    movement = 'down' if schange < 0 else 'up'
    print( format("{} is {} for the day. Current price is {}"), name, movement, scurr) )
    print( format('The price moved {} to the {}side today.',abs(schange), movement) )
    print('-----------------------')

关于python - 我怎样才能使这段代码更加Pythonic——具体来说,将一些东西合并到一个函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32723600/

相关文章:

python - 异步中的奇怪断言错误

python - 检查文本列 pandas 中停用词的数量

python 包 : how to depend on the latest version of a separate package

python - 类型错误 : writerows() argument must be iterable

python - 在 tqdm 中的 for 循环后更改描述

python - 无法使用 ShellExecute 打开超链接失败(错误 2)

Python hasattr 与 getattr

python - Pandas :这里的内存泄漏在哪里?

python - 具有DNN的OpenCv

python - numpy loadtxt、unicode 和 python 2 或 3