简体   繁体   English

python if语句语法错误?

[英]python If statement Syntax error?

new to python, currently reading diveintopython and trying to run the following code from the book: python的新手,目前正在阅读diveintopython并尝试运行书中的以下代码:

def buildConnectionString(params):
   """Build a connection string from a dictionary of parameters.

      Returns string."""
      return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
      myParams = {"server":"mpilgrim", \
                  "database":"master", \
                  "uid":"sa", \
                  "pwd":"secret" \
                  }
    print buildConnectionString(myParams)

Now when i hit enter, Python shell says the if statement has a syntax error??现在当我回车时,Python shell 说if语句有语法错误?? I'm running Python 2.7.我正在运行 Python 2.7。

The code itself is working (I just tried it).代码本身正在运行(我刚刚尝试过)。 A possible reason for errors is inconsistent indentation.错误的一个可能原因是不一致的缩进。 It seems that your lines start with different numbers of spaces (or tabs).您的行似乎以不同数量的空格(或制表符)开头。 Try changing the the blank space in the beginning of each indented line to, say, four spaces, and try running the script again.尝试将每个缩进行开头的空格更改为四个空格,然后再次尝试运行脚本。

The error is in line 5: the return should be indented at the level of the opening """ of the function.错误在第 5 行: return应在函数开头"""的级别缩进。

However, you shouldn't be entering that code in the shell - do it in a text editor.但是,您不应该在 shell 中输入该代码 - 在文本编辑器中输入。

I have solved your issue and i am uploading the proper syntax of code我已经解决了你的问题,我正在上传正确的代码语法

def buildConnectionString(params):
   return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
    myParams = {"server":"mpilgrim", \
                  "database":"master", \
                  "uid":"sa", \
                  "pwd":"secret" \
                }
print (buildConnectionString(myParams))

I hope this will helpful as well as useful for you !!我希望这对你有用,也对你有用!!

输出

Looks like your indentation levels are wrong.看起来您的缩进级别是错误的。 Looking at your pasted code, I would guess that you are mixing tabs and blanks, so you are using a "bad" editor.查看您粘贴的代码,我猜您正在混合制表符和空格,因此您使用的是“坏”编辑器。 Use an editor which replaces tabs by blanks.使用用空格替换制表符的编辑器。

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

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