0

I wrote a code and it is getting compiled on my PC with Python3. But Showing error while uploading to Codechef server. Please suggest, I am coding for the first time in Python 3.

Traceback (most recent call last):
  File "/run-ls7W2DcLmzUs9GNKbLGN/solution.py", line 41, in <module>
    l,r,k=map(int,input().split())
  File "<string>", line 1
    9 23 1
       ^
SyntaxError: invalid syntax

1 Answer 1

4

You're using python2.x which evaluates the string you enter for input. Change the function from input to raw_input and you should be all set.

If you want the code to work for both python2.x and python3.x, you could do a simple little hack like this at the top of your script:

try:
    #This raises `NameError` on python3.x since `raw_input` is renamed to `input`
    input = raw_input
except NameError: 
    pass

It's not pretty, but it works (and I've used things like this on occasion). Ultimately, this shadows the builtin input on python2.x, but that's really not a big deal. You probably don't want to be using that builtin for any serious coding anyway.

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

3 Comments

Or actually use Python 3.x
If you're writing backwards compatible code, I'd recommend doing it the other way: if sys.version_info >= (3,): raw_input = input, so you don't confuse Python 2 programmers.
@RoadieRich -- Yeah, I've done that one too. Tomato-tomato as far as I see it. My way avoids an extra import, but that's probably not much of a concern for most scripts.

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.