tags:

views:

218

answers:

3

When running the following code, which is an easy problem, the Python interpreter works weirdly:

n = input()
for i in range(n):
    testcase = raw_input()
    #print i
    print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]

The problem consists in taking n strings and deleting a single character from them. For example, given the string "4 PYTHON", the program should output "PYTON". The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?

EDIT: I'm working under Python 2.5, 32 bits in Windows.

+4  A: 

Are you sure that the problem is the print i statement? The code works as expected when I uncomment that statement and run it. However, if I forget to enter a value for the first input() call, and just enter "4 PYTHON" right off the bat, then I get:

"SyntaxError: unexpected EOF while parsing"

This happens because input() is not simply storing the text you enter, but also running eval() on it. And "4 PYTHON" isn't valid python code.

MJ
I know, "4 PYTHON" was just an example of the way strings are formatted. The interpreter gives me an EOF even if I assign a value for n.
fmartin
you need raw_input; not input(). Input() expects a valid Python expression. read http://docs.python.org/library/functions.html#input
NicDumZ
+1  A: 

This worked for me too, give it a try...

n = raw_input()
n = int(n)
for i in range(n):
  testcase = raw_input()
  print i
  print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]

Note the n = int(n)

PS: You can continue to use n = input() on the first line; i prefer raw_input.

nik
This works, but I still don't get why it doesn't when using input().
fmartin
+1  A: 

I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.

Do you always get that error? Can you post a transcript of your interactive session, complete with stack trace?

John Y
"complete with stack trace?" This was it; when the first value was typed in it was fetched by another input() in the stack.
fmartin