Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error on the definition of a function in python which seems valid

Tags:

python

sh

When I define a function in this code:

def is_palindrome(seq):
    s=seq[::-1]
    if s==seq:
         return True
    else:
         return False

myfile=open('palindrome.txt','r')
for line in myfile:
    if is_palindrome(line.srtrip()):
        print(line,end='')
myfile.close()

It returns this error message in my console:

./palindrome.py: line 1: syntax error near unexpected token `('
./palindrome.py: line 1: `def is_palindrome(seq):'

and I don't know what's wrong here.

like image 237
Itachi Tensie Avatar asked Dec 11 '13 20:12

Itachi Tensie


1 Answers

You're executing your script as a *sh script. You should do python palindrome.py

Indeed, the error message you get is typically an error of *sh script... When you're calling the script via ./palindrome.py, it executes it with the first interpreter which matches. It seems to be a *sh interpretor here, from your Linux environnement.

To avoid that, the best method is to add #!/usr/bin/env python at the first line of your Python script, which'll force your command line to use the Python interpretor instead of your *sh interpretor.

NB: *sh here represented any derivate of sh: bash, zsh, etc.

like image 180
Maxime Lorant Avatar answered Sep 19 '22 10:09

Maxime Lorant