程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了除了 Python 中的异常错误处理不起作用大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决除了 Python 中的异常错误处理不起作用?

开发过程中遇到除了 Python 中的异常错误处理不起作用的问题如何解决?下面主要结合日常开发的经验,给出你关于除了 Python 中的异常错误处理不起作用的解决方法建议,希望对你解决除了 Python 中的异常错误处理不起作用有所启发或帮助;

我正在尝试从所有与 FTSE250 相关的股票中获取股票市场信息。 我使用 Yahoo_Fin 这样做。该代码有效,但我收到一个错误,提示股票已退市。 因此,我试图放入一个异常代码。我阅读了有关 try 和 except 库的文档,但找不到正确的答案。我没有收到语法错误,但除了异常代码没有任何作用。

编辑:将两个例外设置为有效,以下是更新后的代码。

index_df = pdr.get_data_yahoo(index_name,start_date,END_DATE,progress=falsE)
index_df['Percent Change'] = index_df['Adj Close'].pct_change()
index_return = (index_df['Percent Change'] + 1).cumprod()[-1]

for ticker in tickers:
    # Download historical data as CSV for each stock (makes the process faster)
  try:
      df = pdr.get_data_yahoo(ticker,progress=falsE)
      df.to_csv(f'{ticker}.csv')
  except: 
    except Exception: 
    if ticker not in tickers:
    next(ticker)

for ticker in tickers:
  try:

   # CalculaTing returns relative to the market (returns multiplE)
    df['Percent Change'] = df['Adj Close'].pct_change()
    stock_return = (df['Percent Change'] + 1).cumprod()[-1]
    
    returns_multiple = round((stock_return / index_return),2)
    returns_multiples.extend([returns_multiple])

  except Exception: 
   if ticker not in tickers:
    next(ticker)

解决方法

你的例外对我来说没有意义。您正在遍历代码,然后检查代码是否不在代码中。这将始终为 false,因此您的“下一个”语句永远不会执行,它只会继续执行

看起来你想要的是这样的

for ticker in tickers:
    # Download historical data as CSV for each stock (makes the process faster)
    try:
        df = pdr.get_data_yahoo(ticker,start_date,END_DATE,progress=falsE)
        df.to_csv(f'{ticker}.csv')

        # CalculaTing returns relative to the market (returns multiplE)
        df['Percent Change'] = df['Adj Close'].pct_change()
        stock_return = (df['Percent Change'] + 1).cumprod()[-1]

        returns_multiple = round((stock_return / index_return),2)
        returns_multiples.extend([returns_multiple])

        #change the name of the stock index
        print (f'Ticker: {ticker};  Returns Multiple against FTSE 250 : {returns_multiplE}\n')
        time.sleep(1)
 
    except IndexError:
        print(f"Error in ticker: {ticker},skipping...")

根据回溯的内容传递正确的 except 条件的位置(无法判断是 FileNotFoundError 还是 IndexError)。但我认为您想要做的就是处理列表中的下一个代码?

大佬总结

以上是大佬教程为你收集整理的除了 Python 中的异常错误处理不起作用全部内容,希望文章能够帮你解决除了 Python 中的异常错误处理不起作用所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Python除了