[Tutor] Error message...

Steven D'Aprano steve at pearwood.info
Thu Aug 23 18:26:15 CEST 2012


On 24/08/12 01:33, Victoria Homsy wrote:

> Dear All - sorry to bother you. I just tried to run this program:
>
>
> def isPalindrome(s):
> if len(s)<= 1: return True
> else: return s[0] == s[-1] and isPalindrome (s[1:-1])
> isPalindrome('aba')
>
>
> However when I run it in terminal it doesn't give me any answer -
>True or False. (I want the program to tell me whether the input
>string is True or False). In order to get an answer, I assume I
>would need to tell the program to print something. However I'm
>not sure where in the program I would do this. I tried this:
>
> def isPalindrome(s):
> if len(s)<= 1: return True and print "True"
> else: return s[0] == s[-1] and isPalindrome (s[1:-1])
> isPalindrome('aba')
>
> However, this does not work - I get another error message.

Would you like to tell us what error message you get, or should we
try to guess? I love guessing games!

Ah, who am I fooling? I hate guessing games. It's always best if
you copy and paste the full traceback you get, starting with the
line

"Traceback (most recent call last)"

all the way to the end of the error message.


In this case, I can guess that you are getting a SyntaxError. Am I
close? If I'm right, you can read the SyntaxError and it will give
you a hint as to where to look for the error:

py> if len(s) <= 1: return True and print True
   File "<stdin>", line 1
     if len(s) <= 1: return True and print True
                                         ^
SyntaxError: invalid syntax


See the caret ^ printed just below the offending line of source
code and just above the message that it is a syntax error? In the
terminal window, that will point to the first part of the line
which Python doesn't understand.

In this case, you're giving Python instructions in English, and it's
not that smart. A human being might understand what you mean by
"return True and print True", but that's invalid Python code. You
need to separate that into two separate operations:

1) The isPalindrome function you write is responsible for returning
the True or False flag, nothing more.

2) The piece of code that calls the function is responsible for
printing the flag.


So in this case, your isPalindrome function must return a flag:


def isPalindrome(s):
     if len(s) <= 1: return True
     else: return s[0] == s[-1] and isPalindrome (s[1:-1])


And the caller is responsible for printing the result:

result = isPalindrome('aba')
print result


Those two lines can be simplified to one line:

print isPalindrome('aba')


-- 
Steven


More information about the Tutor mailing list