I’m making a basic Palindrome Checker in python for a small project. I have searched around and found no answer to this.
I am using the following code near the end of the script:
if String1 == String2:
print("Yes")
else:
print("No")
I receive a syntax error when I run this code. String1 is the text entered by the user and String2 is the text in reverse, which I develop earlier. I am running Python 3.2.3
Thanks in advance
I am using String2 == String1[::-1] for my Palindrome check and the error I receive is
SyntaxError: invalid syntax
Edit:
This is my exact code however I’m not exactly sure where to put else: I have tried it multiple times on both new lines and on the line before with no success. String1 in this instance is “racecar”
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import easygui as eg
>>> String1 = eg.enterbox(msg="Enter a Word")
>>> String2 = String1[::-1]
>>> if String1 == String2:
print("Yes")
Yes
>>> else:
SyntaxError: invalid syntax
>>>
Using
[::-1]to check for palindromes should work like a charm:There’s something in your code that you’re not showing us. You need to paste a larger code snippet, or the actual traceback you receive.
And, now to account for your pasted traceback – you did not indent the
printcommand after theifstatement. Because theifclause ended immediately it makes no sense (syntax error) to provide an else. Indentation is syntax in Python. You need it to look like this:The spacing is mandatory.