如何将while循环中的if语句分解为两个单独的函数?

2024-10-03 17:19:10 发布

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

这个想法是保持重复输入,除非输入'm'。我正试图通过latinize_语句函数在'else:'之后输入_latin(确切地说)

但是,如果没有必要,最好不要改变拉丁化_语句的功能,因此以后可以单独测试

编写一个程序,反复要求用户输入句子并打印 找出那些句子的拉丁语版本。 用户可以输入“m”退出程序

def main():
    """Set up the main function to process the latin format"""
    sentence = input_latin("Enter English sentence: ")
    print_latin(sentence)


def input_latin(words):
    """Make the input repeat over unless encounter 'm'"""
    looping = False
    while not looping:
        sentence = input(words)
        if sentence == 'm':
            looping = True
            return sentence
        else:
            latin = latinize_sentence(sentence)
            return latin


def latinize_sentence(sentence):
    """return the Bee Latin version of the sentence."""
    latin = sentence.lower().split()
    for word_num in range(len(latin)):
        if latin[word_num][0] in "aeiou" or sentence[word_num][0].isalpha() == False:
            latin[word_num] += 'buzz'
        else:
            latin[word_num] = latin[word_num][1:] + \
                latin[word_num][0]
            latin[word_num] += 'uzz'
    latin = ' '.join(latin)
    return latin
    

def print_latin(sentence):
    """Print out the result"""
    if sentence == 'm':
        print("oodbyeguzz")
    else:
        print("Bee latin = {}".format(sentence))
  
    
main()

示例测试:

测试main()

Bee latin = rytuzz histuzz outbuzz
Enter English sentence: and that #Repeatly
Bee latin = andbuzz hattuzz
Enter English sentence: m #stop repeating until type 'm'
oodbyeguzz
Enter English sentence: this is a longer sentence
Bee latin = histuzz isbuzz abuzz ongerluzz entencesuzz
Enter English sentence: wow and this is even longer than the last
Bee latin = owwuzz andbuzz histuzz isbuzz evenbuzz ongerluzz hantuzz hetuzz astluzz

#Testing latinize_sentence:

english = latinize_sentence("try this out")
print(english)
rytuzz histuzz outbuzz

Tags: theinputreturnenglishmaindefelsenum
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:10

我认为你让事情变得不必要的复杂: 你可以通过以下方式实现这一点:

def latinize_sentence(sentence):
    """return the Bee Latin version of the sentence."""
    latin = sentence.lower().split(" ")
    for word_num in range(len(latin)):
        if (latin[word_num][0] in "aeiou") or (latin[word_num][0].isalpha() == False):
            latin[word_num] += 'buzz'
        else:
            latin[word_num] = latin[word_num][1:] + latin[word_num][0]
            latin[word_num] += 'uzz'
    latin = ' '.join(latin)
    return latin


def print_latin(sentence):
    """Print out the result"""
    print("Bee latin = {}".format(sentence))

def main():
    while(True):
        user_input = input("Enter English sentence: ")
        if(user_input == "m"):
            print("oodbyeguzz")
            break
        else:
            print_latin(latinize_sentence(user_input))

main()

相关问题 更多 >