Python 如何处理for循环中的错误?

Python 如何处理for循环中的错误?,python,pandas,dataframe,Python,Pandas,Dataframe,我在for循环中编写了以下代码来处理我遇到的错误,但在这个块中似乎无法使用continue语句和except关键字。我怎样才能修好它 最初,我想提出一个异常来显示表中不存在的键,并让for循环在遇到这些键错误时继续 for i in range(1000): # do something try: u= str(df.loc[item_a, 'E']) v= str(df.loc[item_a, 'D']) w= str(df.loc[item_b, 'E']

我在for循环中编写了以下代码来处理我遇到的错误,但在这个块中似乎无法使用continue语句和except关键字。我怎样才能修好它

最初,我想提出一个异常来显示表中不存在的键,并让for循环在遇到这些键错误时继续


for i in range(1000):

# do something 

 try:
    u= str(df.loc[item_a, 'E'])
    v= str(df.loc[item_a, 'D'])

    w= str(df.loc[item_b, 'E'])
    x= str(df.loc[item_b, 'D'])

 continue

 except KeyError:

 raise Exception('KeyError: {} do not exist in the table.'.format(a))


# do something else

如果引发错误,执行将停止。您可以将continue语句放在except块中。这将允许您继续进行循环。在点击continue语句之前,请确保打印/注销您需要的任何信息

for i in range(1000):

   # do something 

   try:
      u= str(df.loc[item_a, 'E'])
      v= str(df.loc[item_a, 'D'])

      w= str(df.loc[item_b, 'E'])
      x= str(df.loc[item_b, 'D'])

   except KeyError:
      print('KeyError: {} does not exist in the table.'.format(your_variable))
      continue

修改后,我收到警告:“继续”外部循环。我已检查continue语句是否与print语句对齐。如何修复?听起来你没有正确缩进。你的代码是否像我的回答那样缩进了?还是你的问题?如果尚未缩进try和except块,则不能使用continue,因为该关键字仅适用于循环内部。似乎keyrorm可能出现在块“u=str(df.loc[item_a,'E'])v=str(df.loc[item_a,'D'])中,或者出现在“w=str(df.loc[item_b,'E'])x=str(df.loc[item_b,'D'])”中。如何捕获这两个异常?谢谢。由于两个块都在try下,您将捕获这些异常。如果您希望两个块都有单独的消息,请在try-except中包装前两行,然后在另一个try-except中包装后两行。