phrase = input("Enter a phrase")
rev_phrase = reversed(phrase)
i = len(phrase)
while i >= 0:
if phrase[i] != rev_phrase[i]
print(phrase + " is not a palindrome")
exit()
i -= 1
print(phrase + "is a palindrome")
Trying to reverse the order of a phrase, then check if it spells out the same thing before reversing. However, I am getting an error in line 5 where I am reversing the phrase.
My Error Message:
C:\Users\Mikhail\PycharmProjects\FirstUse\venv\Scripts\python.exe "C:/Users/Mikhail/PycharmProjects/FirstUse/venv/Exersise Six.py"
File "C:/Users/Mikhail/PycharmProjects/FirstUse/venv/Exersise Six.py", line 5
if phrase[i] != rev_phrase[i]
^
SyntaxError: invalid syntax
Process finished with exit code 1
You need to have : at the end of line #5.
EDIT:
You should keep in mind that 'Anna' is considered palindrome as well as 'Step on no pets', 'Was it a car or a cat I saw?'
phrase = input("Enter a phrase")
rev_phrase = reversed(phrase)
i = len(phrase)
while i >= 0:
if phrase[i] != rev_phrase[i]:
print(phrase + " is not a palindrome")
exit()
i -= 1
print(phrase + "is a palindrome")
Now I am getting this error in #line 5:
C:\Users\Mikhail\PycharmProjects\FirstUse\venv\Scripts\python.exe "C:/Users/Mikhail/PycharmProjects/FirstUse/venv/Exersise Six.py"
Enter a phrasepop
Traceback (most recent call last):
File "C:/Users/Mikhail/PycharmProjects/FirstUse/venv/Exersise Six.py", line 5, in <module>
if phrase[i] != rev_phrase[i]:
IndexError: string index out of range
Process finished with exit code 1
Python uses zero based indexing therefore:
>>> a = 'abc'
>>> len(a)
3
>>> a[3]
/../
IndexError: string index out of range
>>> [a.index(char) for char in a]
[0, 1, 2]
in python indexes are zero-based, thus max index in
len(phrase)-1
now, unless you are required (e.g. homework) to use while loop and indexes, there are better , more pythonic ways to complete the task
using slices
if phrase == phrase[::-1]
print("it's palindrome")
else:
print("not palindrome")
or even as oneliner
print("it's palindrome" if phrase == phrase[::-1] else "not palindrome")
if you want to compare char by char
for c1, c2 in zip(phrase, phrase[::-1]):
if c1 != c2:
print("not palindrome")
break
else:
print('palindrome')
if all(c1 == c2 for c1, c2 in zip(phrase, phrase[::-1])):
print("palindrome")
else:
print('not palindrome')