Python如何停止循环

2024-10-05 14:22:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个程序,基本上从一个句子中获取每个单词,并将它们放入回文检查器中。我有一个函数可以删除句子中的任何标点符号,一个函数可以查找句子中的第一个单词,一个函数可以在句子的第一个单词之后获取其余单词,还有一个函数可以检查回文。你知道吗

#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)
现在我正在尝试使用字符串“弗兰克很棒!!!!”但我的问题是我不知道如何阻止程序循环。程序不断获取字符串的“伟大”部分,并将其放入回文检查器中,以此类推。我怎样才能让它停下来,让它只检查一次?你知道吗


Tags: 函数程序lenreturnifdeflocation单词
1条回答
网友
1楼 · 发布于 2024-10-05 14:22:03

你可以这样阻止它

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)

相关问题 更多 >