Leon WANG
Leon WANG

Reputation: 103

How to handle no input using input() function in Python?

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.

Upvotes: 2

Views: 3145

Answers (2)

Abhijith Asokan
Abhijith Asokan

Reputation: 1875

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.

Upvotes: 1

firesurfing
firesurfing

Reputation: 155

you can use raw_input with a default value

x = raw_input() or 'default_value'

Upvotes: 1

Related Questions