首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何忽略Python中的"KeyError“

如何忽略Python中的"KeyError“
EN

Stack Overflow用户
提问于 2020-05-24 05:44:26
回答 1查看 480关注 0票数 0

我正在尝试使用api“yfinance”分析python中的股票。我让程序在大多数时候都运行得很好。但是,当它不能“找到”其中一个字段时,它将遍历一个错误(KeyError)。下面是我的代码片段。

代码语言:javascript
运行
复制
import yfinance as yf
stock = yf.Ticker(stock)
pegRatio = stock.info['pegRatio']
print(pegRatio)
if pegRatio > 1:
    print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
    print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
    print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")

这是错误回溯(最近一次调用):第29行,在行业=Stock.info‘行业’KeyError:‘行业’中。

我的主要问题是如何让代码基本上忽略错误并运行其余代码?

EN

回答 1

Stack Overflow用户

发布于 2021-07-11 07:58:24

Python中的错误处理

就像Nicolas commented一样,你会在网上找到很多教程、博客文章和视频。还有一些基本的Python书籍,涵盖了“错误处理”。

Python中的控制结构至少由两个关键字tryexcept组成,它们通常被命名为try-except block。还有两个可选关键字elsefinally

如何包装失败的语句

代码语言:javascript
运行
复制
import yfinance as yf

try: # st art watching for errors
  stock = yf.Ticker(stock)  # the API call may also fail, e.g. no connection
  pegRatio = stock.info['pegRatio']  # here your actual exception was thrown
except KeyError:  # catch unspecific or specific errors/exceptions
  # handling this error type begins here: print and return
  print "Error: Could not find PEG Ratio in Yahoo! Finance response!"
  return 

# the happy path continues here: with pegRatio
print(pegRatio)
if pegRatio > 1:
    print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
    print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
    print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61978929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档