Mokolodi1
Mokolodi1

Reputation: 119

for loop nested inside the expression from an if statement

This is a question about syntax more than anything. I am pretty sure that I am almost right, but not quite. I'm trying to put a for loop inside of the expression for an if statement.

A mock-up of what I think it should be for a simple palindrome tester:

toTest = "asdffdsa"
if toTest[i]==toTest[-i] for i in range(len(toTest)/2):
    print("It's a palendrome!")

Thanks in advance for your help!

Upvotes: 0

Views: 1644

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601529

I guess you mean

if all(toTest[i] == toTest[-i] for i in range(len(toTest)/2)):
    print("It's a palindrome!")

Note that it would be much easier to do

if toTest == toTest[::-1]:
    print("It's a palindrome!")

Upvotes: 7

mau5padd
mau5padd

Reputation: 405

While it may not be exactly what you're looking for, here is a short-hand to check if a string is a palindrome in Python:

toTest = "asdffdsa"
if toTest == toTest[::-1]: print ("It's a palindrome!")

Upvotes: 1

Related Questions