简体   繁体   中英

python If statement Syntax error?

new to python, currently reading diveintopython and trying to run the following code from the book:

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?? I'm running 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.

However, you shouldn't be entering that code in the shell - do it in a text editor.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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