简体   繁体   English

如何解决Python 2.7中以下代码的语法错误?

[英]How can I solve syntax error for the following code in Python 2.7?

I have used the following code for optimizing a problem via pyomo , coopr . 我使用以下代码通过pyomocoopr优化问题。

However the compiler gives an error, as follows: 但是,编译器给出了一个错误,如下所示:

invalid syntax 无效的语法

I tried to use correct syntax but I can not find the error: 我尝试使用正确的语法,但找不到错误:

model = AbstractModel()
model.x = Var(initialize = 1.5)
model.y = Var(initialize = 1.5)
import pyomo
from coopr.pyomo import *
def rosenbrock(model):
    return (1.0-model.x)**2 \
           + 100.0*(model.y - model.x**2)**2
model.obj=Objective(rule=rosenbrock, sense=minimize)
SyntaxError: invalid syntax

That code appears to be syntactically valid. 该代码在语法上似乎是有效的。 Indeed I have just successfully compiled it in Python 3.6 实际上,我已经在Python 3.6中成功编译了它

Two possibilities occur to me: 我想到了两种可能性:

  1. There is a problem with your line continuation. 您的行继续存在问题。 Note that the backslash must be followed only by exactly the new line character. 请注意,反斜杠后必须仅紧跟换行符。 If you have additional white space then this will cause an error. 如果您还有其他空格,则将导致错误。 For that reason, Python programmers are recommended to avoid line continuation. 因此,建议Python程序员避免行继续。

  2. The environment in which this code is running is a specialised embedded Python with some special constraints of which I am not aware. 运行此代码的环境是一个专用的嵌入式Python,但我不知道其中有一些特殊的约束。

Hope one of these helps ... 希望这些帮助之一...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM