Python Forum

Full Version: New to programming, loop question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, can anyone please explain the for loop here?
def is_palindrome(s):
    s = s.replace(" ", "")
    for i in range(0, int(len(s)/2)):
        if s[i] != s[len(s)-i-1]:
            return False
    return True


if __name__ == "__main__":
    test1 = is_palindrome("racecar")
    print("is_palindrome(\"racecar\") is:", test1)
the range is 0 to int(string length/2) -- stops after middle of string is reached
it then checks to see if current character (i) is equal to the character at the same distance from end

example: say word is 'civic'
Output:
length of word / 2 is 5/2 = int(2.5) = 2 range = 0 - 2 .......................................................... | Iter. | i | s[i] | len(s)-i-1 | s[len(s)-i-1] | RetVal | .......................................................... | 1 | 0 | 'c' | 5-0-1 = 4 | 'c' | True | .......................................................... | 2 | 1 | 'i' | 5-1-1 = 3 | 'i' | True | .......................................................... s is a palindrome
if you add a 'k' ro civic ('civick')
the loop will fail on first iteration and return False.