0

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.

3
  • Which version of python? The for loop works fine for me with 'print i' uncommented on windows python 2.6.2c1 Commented Jun 11, 2009 at 19:10
  • worked fine for me on python 2.6.2 on linux. Commented Jun 11, 2009 at 19:11
  • I also got it to run without complain - Python 2.5.1 OS X Commented Jun 11, 2009 at 19:16

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
you need raw_input; not input(). Input() expects a valid Python expression. read docs.python.org/library/functions.html#input
1

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?

1 Comment

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

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.

1 Comment

This works, but I still don't get why it doesn't when using input().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.