0

I just started learning python and was writing programs in Python GUI Shell IDLE. The code is the following:

>>> 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":"mpligrim",\
                "database":"master",\
                "uid":"sa",\
                "pwd":"secret"
                }
        print(buildConnectionString(myParams))

I am facing a problem while I I try to run this program. In IDLE, when I click on Run Module, a new windows opens up saying "Invalid Syntax" Here's the screenshot: enter image description here

I am not able to find how to run this and would appreciate the help in proceeding further with this.

Link: https://i.stack.imgur.com/oJZb1.png

Cipher
  • 5,894
  • 22
  • 76
  • 112

2 Answers2

1

It looks like you've copied the header output from a shell window into your module window: You don't want your file to look like this:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print "Hello World"

You just want this:

print "Hello World"

Delete all that other stuff.

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
0

Move the if __name__ == "__main__": back by four spaces; your spacing in IDLE is different from that which you've copied and pasted here, the code works fine:

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":"mpligrim",\
        "database":"master",\
        "uid":"sa",\
        "pwd":"secret" }

    print(buildConnectionString(myParams))

Open up a new window in idle and create this as a .py script. Then press F5 to execute, or go to run -> run module

Ben
  • 51,770
  • 36
  • 127
  • 149
  • You mean like this>> http://i.imgur.com/RjWQJ.png ? Still getting the same 'invalid syntax' error. – Cipher Sep 24 '11 at 12:45
  • Your spacing is still slightly incorrect, the dictionary myParams has too many spaces for the rows after the first. You might want to look at [this](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) for the `if` statement. It looks like you're trying to run it all on the shell, as you're not actually running a script the `if` won't work. Open up a new window in IDLE and copy this into there. Then run module ( `F5` ). It worked for me once the spacing has been changed, I've changed my answer to reflect this. – Ben Sep 24 '11 at 13:00
  • Phew! So much for just spacing. – Cipher Sep 24 '11 at 13:15