1

I have learned c and c++, and I am trying to learn python these days...but I have ran into a problem I just can't understand...

a,b = input().split()
print(a)
print(b)

if I execute this short code, "SyntaxError: unexpected EOF while parsing" this is the error message I get...I have looked for the questions with the same error message, but it didn't solve my problem...

in order to understand the problem, I've tried various things, and I figured something which I find kinda weird...

a = input()
print(a)

if I execute this code, it works well when I input a integer value, but when I input a string, "SyntaxError: invalid syntax" this kind of error message appears...

am I doing sth wrong? or is there sth that I don't know that makes this code look flawless to me when this is indeed wrong?

JJJ
  • 15
  • 4
  • Both codes are working all right for me. What python version are you using and what is your system? – rnso Jan 10 '18 at 08:09

1 Answers1

3

Here is your code:

$ cat a.py
a,b = input().split()
print(a)
print(b)

Let's run it first under python3:

$ python3 a.py 
1 2
1
2

(1 2 is what I typed at the prompt.)

Here is the same code running under python2:

$ python2 a.py 
1 2
Traceback (most recent call last):
  File "a.py", line 1, in <module>
    a,b = input().split()
  File "<string>", line 1
    1 2
      ^
SyntaxError: unexpected EOF while parsing

This shows the same error that you report.

The issue is that input means something different in python3 than it did in python2. Under python3, input simply reads in as a string what the user types. Under python2, input both reads user input and evaluates it.

To make the code work the same under python2 as it did under python3, we need to replace input with raw_input:

$ cat b.py
a,b = raw_input().split()
print(a)
print(b)

And, observe:

$ python2 b.py
1 2
1
2

If you have a choice, you should be using python3. Python2 is approaching end-of-life.

John1024
  • 109,961
  • 14
  • 137
  • 171