2

I tried to write a program which requests user to choose an option, however, Python always show an error message if user choose nothing and only input ENTER. Here is an example

tmp=input("Choose program type:1.C++;2.Python;3.PERL (ENTER for default 2.Python)")
print tmp, type(tmp)   #test input
if len(str(tmp)) == 0:
  tmp=0

if tmp == 1:
  print "User choose to create a C++ program.\n"
  DFT_TYPE=".cpp"
elif tmp ==2:
  print "User choose to create a Python program.\n"
  DFT_TYPE=".py"
elif tmp ==3:
  print "User choose to create a PERL scripts.\n"
  DFT_TYPE=".pl"
else:
  print "User choose incorrectly. Default Python program would be     created.\n"  
DFT_TYPE=".py"

if I input ENTER only, I got error message like below

Traceback (most recent call last):   File "./wcpp.py", line 17, in <module>
    tmp=input()   File "<string>", line 0

    ^ SyntaxError: unexpected EOF while parsing

How to handle such case if user input nothing? Any further suggestion would be appreciated.

1
  • Works fine in Python 3 btw. Not sure if it's an earlier version issue Commented Jan 3, 2018 at 3:36

2 Answers 2

1

Since you are using python 2, use raw_input() instead of input().

tmp=raw_input("Choose program type:1.C++;2.Python;3.PERL (ENTER for default 2.Python)")
...
...
if tmp!='':
    tmp = int(tmp)
    pass #do your stuff here
else:
    pass #no user input, user pressed enter without any input.

The reason you are getting error is because in python2 input() tries to run the input statement as a Python expression.

So, when user gives no input, it fails.

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

Comments

1

you can use raw_input with a default value

x = raw_input() or 'default_value'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.