pythoninputcommand-linepython-2.x

Command-line input causes SyntaxError


I have this code:

# Compare phone number  
phone_pattern = '^\d{3} ?\d{3}-\d{4}$'

phoneNumber = str(input("Please enter a phone number: "))

if re.search(phone_pattern, "258 494-3929"):  
    print "Pattern matches"
else:  
    print "Pattern doesn't match!"

When I try to type the phone number in response to the input prompt, I get an error:

Please enter a phone number: 258 494-3929  
Traceback (most recent call last):  
   File "pattern_match.py", line 16, in <module>  
     phoneNumber = str(input("Please enter a phone number: "))  
   File "<string>", line 1  
     258 494-3929  
         ^
SyntaxError: invalid syntax

Why does this happen?


This question is about a specific error that comes up specific to Python 2.x while attempting to process user input. Usually this comes from a failed attempt at implementing Asking the user for input until they give a valid response.

See also Why does the IPython REPL tell me "SyntaxError: unexpected EOF while parsing" as I input the code? for a related problem when using IPython.


Solution

  • You should use raw_input instead of input, and you don't have to call str, because this function returns a string itself:

    phoneNumber = raw_input("Please enter a phone number: ")