Search code examples
pythonloopspython-3.xpalindrome

Python How to Stop my Loop


I made a program in python that basically gets each word from a sentence and puts them into a palindrome checker. I have a function that removes any punctuation put into the sentence, a function that finds the first word in the sentence, a function that gets the rest of the words after the first word of the sentence, and a function that checks for palindromes.

#sent = input("Please enter a sentence: ")#sent is a variable that allows the user to input anything(preferably a sentence) ignore this

def punc(sent):
    sent2 = sent.upper()#sets all of the letters to uppercase
    sent3=""#sets sent3 as a variable
    for i in range(0,len(sent2)):
        if ord(sent2[i])==32 :
            sent3=sent3+sent2[i]
        elif ord(sent2[i])>64 and ord(sent2[i])<91:
            sent3=sent3+sent2[i]
        else:
            continue
    return(sent3)


def words(sent):
    #sent=(punc(sent))
    location=sent.find(" ")
    if location==-1:
         location=len(sent)
    return(sent[0:location])

def wordstrip(sent):
    #sent=(punc(sent))
    location=sent.find(" ")
    return(sent[location+1:len(sent)])

def palindrome(sent):
    #sent=(words(sent))
    word = sent[::-1]
    if sent==word:
        return True
    else:
        return False



stringIn="Frank is great!!!!"
stringIn=punc(stringIn)
while True:
   firstWord=words(stringIn)
   restWords=wordstrip(stringIn)
   print(palindrome(firstWord))
   stringIn=restWords
   print(restWords)

Right now I am trying to use the string "Frank is great!!!!" but my problem is that I'm not sure how to stop the program from looping. The program keeps getting the "GREAT" part of the string and puts it into the palindrome checker and so on. How do I get it to stop so it only checks it once?


Solution

  • you can stop it like that

    while True:
       firstWord=words(stringIn)
       restWords=wordstrip(stringIn)
       #if the word to processed is the same as the input word then break
       if(restWords==stringIn) : break  
       print(palindrome(firstWord))
       stringIn=restWords
       print(restWords)