Python Forum
New to programming, loop question
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New to programming, loop question
#1
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)
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  General Programming Question with Dictionary giddyhead 12 2,715 Jan-10-2022, 10:12 AM
Last Post: Pedroski55
Big Grin General programming question (input string)[ jamie_01 2 1,597 Jan-08-2022, 12:59 AM
Last Post: BashBedlam
  A question about 'Event loop is closed' fc5igm 2 2,207 Oct-05-2021, 02:00 AM
Last Post: fc5igm
Exclamation question about input, while loop, then print jamie_01 5 2,672 Sep-30-2021, 12:46 PM
Last Post: Underscore
  for loop question KEYS 1 1,729 Oct-27-2020, 11:42 PM
Last Post: jefsummers
  Netmiko Loop question sc00ter 2 3,323 Oct-24-2020, 10:54 PM
Last Post: sc00ter
  while loop question KEYS 2 2,017 Sep-26-2020, 11:02 PM
Last Post: KEYS
  while loop question spalisetty06 2 1,852 Aug-13-2020, 04:18 PM
Last Post: buran
  question about for loop Than999 5 2,485 Jun-09-2020, 02:16 PM
Last Post: Emekadavid
  Linear Programming (PuLP) - loop for constraints littleangel83 1 3,807 Jun-02-2020, 02:39 PM
Last Post: littleangel83

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020