views:

76

answers:

4

Hello,

I'm learning python. It gives syntax error in this script. I'm unable to figure out.

import exceptions
class FOUND(Exception): pass

x = [1,2,3,4,56,73,29,35,12,32,63,12,76,75,89]


while True:

    try:
        test = int(raw_input('Enter integer to be checked in list:'))
        count = -1
        for y in x:
            count += 1
            if y == test:
                raise FOUND
    except ValueError as e:
        print "Not a valid integer (%s)"%(e)
    except FOUND:
        print "Found (%d) at (%d)"%(test,count)
    else:
        print "Not found ,Appending (%d) to list at location (%d)"%(test,count+1)
        x.append(test)
    finally:
        print "The List:"
        print x
        print " "

Invalid syntax & it highlights closing double quote in this line: print "Not a valid integer (%s)"%(e)

+1  A: 

You need an empty line between the class ... and x = ...

Wim
pecker
The script works without a blank line there when cut-and-pasted into a Python file. If you'd type it into an interactive prompt, a blank line would be needed, however.
Pär Wieslander
+1  A: 

Try except ValueError as e:, the older syntax you use is invalid in Python 3.

Tamás
now it again throws invalid syntax but highlighting the closing quote of `print "Not a valid integer (%d)"%(e)`
pecker
@pecker: you're using python-2.x code with a py3k interpreter. I could tell which error is going to be thrown after you'll fixed this one.
SilentGhost
if you are indeed using python 3 then `print` is a function, and needs to be called like `print("Not a valid integer (%d)" % e)` or better yet `print("Not a valid integer(", int(e), ")")` (not sure if the % syntax even still works in py3k)
Carson Myers
+1  A: 

Your code (cut and pasted, no alterations) works fine for me (Python 2.5).

BTW, your test = int... line should be after the try (and indented appropriately) and the %d in "Not a valid integer (%d)" should be a %s.

Syntax for exception handling has been changed for Python 3: make sure any help/tutorials you are following are for the same major version of Python you have installed. There have been signficant changes from 2.x to 3.x.

mavnn
+2  A: 

print without brackets is from python 2, if you are using python 3, you need to use print().

You can't format an exception as %d - %d is for integers.

Douglas Leeder