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.
-
Which version of python? The for loop works fine for me with 'print i' uncommented on windows python 2.6.2c1workmad3– workmad32009年06月11日 19:10:26 +00:00Commented Jun 11, 2009 at 19:10
-
worked fine for me on python 2.6.2 on linux.Jack– Jack2009年06月11日 19:11:57 +00:00Commented Jun 11, 2009 at 19:11
-
I also got it to run without complain - Python 2.5.1 OS XJarret Hardie– Jarret Hardie2009年06月11日 19:16:08 +00:00Commented Jun 11, 2009 at 19:16
3 Answers 3
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.
2 Comments
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
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.