1

Python interpreter gives Syntax error while running below code:

import sys if len(sys.argv) == 3: a=sys.argv[1] b=sys.argv[2] sum=int(a) + int(b) print "The sum is: ", sum elif len(sys.argv) != 3: print "Only two arguments allowed !" else: print "Please enter two numbers as argument with the script. Try again !" 

Error:

luckee@zarvis:~/python$ ./sumtwo.py 5 10 ./sumtwo.py: line 3: syntax error near unexpected token `sys.argv' ./sumtwo.py: line 3: `if len(sys.argv) == 3:' 
2
  • 3
    Your file is interpreted by your shell, not Python interpreter. Try python sumtwo.py or adding #!python as a first file of your file. Commented Jun 16, 2016 at 18:44
  • 1
    Rogalski's got it. Also this is somewhat tangential, but your if and elif clauses cover every possibilty - len(sys.argv) has to be either == 3 or != 3. The else will never get triggered. Commented Jun 16, 2016 at 18:47

1 Answer 1

4

Your file is interpreted by your shell, not Python interpreter. Try specifying binary when running it:

luckee@zarvis:~/python$ python sumtwo.py 5 10 

Alternatively, you may add shebang as a first line of your script.

#!/usr/bin/python import sys if len(sys.argv) == 3: a=sys.argv[1] b=sys.argv[2] sum=int(a) + int(b) print "The sum is: ", sum elif len(sys.argv) != 3: print "Only two arguments allowed !" else: print "Please enter two numbers as argument with the script. Try again !" 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.