首页 > 解决方案 > Python 复杂 IF 语句

问题描述

我在这里遇到一些语法错误,似乎找不到它:

if open_prices[0] > close_prices[0]:
  if (close_prices[0] - low_prices[0]) >= 2*(open_prices[0] - close_prices[0]) and          
     (high_pices[0] - open_prices[0]) <= 0.5*(open_prices[0] - close_prices[0]):
      x = 1

错误是

if (close_prices[0] - low_prices[0]) >= 2*(open_prices[0] - close_prices[0]) and (high_pices[0] - open_prices[0] <= 0.5*(open_prices[0] - close_prices[0]):
                                                                                                                                                          ^
SyntaxError: invalid syntax

我的语法或格式不正确吗?

标签: pythonif-statement

解决方案


您的第二个 if 语句结构错误。Python 遵循严格的缩进规则,当它不知道如何处理一个语句时会抛出一个语法错误,这里你已经留下了一个部分(以 结尾的行and),所以它试图将它解析为一个完整的语句,这显然失败。

一个简单的解决方法是将整个谓词括在括号内(这使其成为单个语句),如下所示:

if ( (close_prices[0] - low_prices[0]) >= 2*(open_prices[0] - close_prices[0]) and         
     (high_pices[0] - open_prices[0]) <= 0.5*(open_prices[0] - close_prices[0]) ):
      x = 1


推荐阅读