如何同时使用main函数和while函数

时间:2019-02-11 04:22:07

标签: python loops while-loop

只要用户不断输入单词,我就会尝试编写一个运行我的函数的循环。 (即,当没有输入任何单词时停止。)

除循环部分外的所有其他东西都在工作。我不知道如何在主函数中使用while函数。

done = False
while not done:

    def main():
        words = str(input("Please enter a word: "))
        words = words.split()
        for word in range(len(words)):
            i = words[word]
            if i[0] in ['a', 'e', 'i', 'o', 'u']:
                words[word] = i+'way'
            elif i[0] not in ['a', 'e', 'i', 'o', 'u']:
                words[word] = i[1:]+i[0]+'ay' 
            else:
                print('STOP')
                done = True
                break
            return ' '.join(words)

    def t(str):
            return str[0]+str[1]

    if __name__ == "__main__":
            x = main()
            print(x)

2 个答案:

答案 0 :(得分:1)

具有主要功能的想法是将所有代码封装在其中,并仅在未将文件作为模块调用时if __name__ == '__main__'才执行。从我的角度来看不是很pythonic,但是它会变成这样:

def t(str):
    # unused function btw
    return str[0]+str[1]

def main():
    done = False
    while not done:

        words = str(input("Please enter a word: "))
        words = words.split()
        for word in range(len(words)):
            i = words[word]
            if i[0] in ['a', 'e', 'i', 'o', 'u']:
                words[word] = i+'way'
            elif i[0] not in ['a', 'e', 'i', 'o', 'u']:
                words[word] = i[1:]+i[0]+'ay' 
            else:
                # this doesn't make any sense
                # you're covering all possible scenarios
                # with the if and elif
                # this code will never be executed
                print('STOP')
                done = True
                break
        # note that this return has to be out of the for
        # otherwise it would only make one iteration
        # probably out of the while loop too
        return ' '.join(words)

if __name__ == "__main__":
        x = main()
        print(x)

答案 1 :(得分:0)

这里是重构,可以进行以下修改。

  • def应该在while循环之外;一次又一次地重新定义相同的功能是没有道理的。
  • read-eval-print循环位于main中,该循环调用pig_latin以获得实际的Pig Latin逻辑。

其他一些在线注释。

def pig_latin(string):
    # Don't use the same variable name for a string and a list
    words = string.split()
    for word in range(len(words)):
        i = words[word]
        if i[0] in ['a', 'e', 'i', 'o', 'u']:
            words[word] = i+'way'
        # no need for "elif", you already tested this
        else:
            words[word] = i[1:]+i[0]+'ay' 
    # Outdented -- don't return too early
    return ' '.join(words)

# Commented out -- this function is not used
"""
def t(str):
        return str[0]+str[1]
"""

def main():
    while True:
        # No need for str(); input always returns a string
        words = input("Please enter a word: ")
        if words == "":
            print('STOP')
            break
        print(pig_latin(words))

if __name__ == "__main__":
    # Put absolutely no real logic here; just dispatch
    main()

请注意如何将所有用户交互都一次隔离,并且翻译文本的实际功能(单独)是分开的。