【问题标题】:Python 3.4.2:My infinite function while loop is not workingPython 3.4.2:我的无限函数 while 循环不起作用
【发布时间】:2015-02-13 12:57:12
【问题描述】:

我的无限 while 循环没有像我预期的那样工作:

def main():
    print("Type 1 to create a file")
    print("Type 2 to read a file")
    print("Type 3 to append a file")
    print("Type 4 to calculate total of file")
    print("Type 5 to end the program")
    choice=input("Select a number:")
    if choice == '1':
            file_create(filename)
    elif choice == '2':
            read_file(filename)
    elif choice == '3':
            append_file(filename)
    elif choice == '4':
            add_numbers(filename)
filename=input("Give a name to your file:")     
while main():
    # ...

这会执行一次main,但不会循环。

【问题讨论】:

标签: python function loops while-loop


【解决方案1】:

Mr.Anyoneoutthere,Sylvain 是绝对正确的。既然你不明白,那我就解释一下。 循环需要一个条件:真或假。 所以当你说:-

while True:
    print('World')

等同于:-

a = 100
while a == 100:
    print('poop')

由于 a == 100 的计算结果为“True”,并开始一个循环,因为您让值保持不变,并开始一个无限循环。但是你可以直接把评价,即'True',直接开始无限循环。

正如你所说:-

while main():
    print('World')

所以现在想想……而 main()……main() 什么?……编译器没有得到任何代码来将某些东西评估为“真”或“假”,并且循环永远不会开始!

所以你需要的正确代码是:-

while True:
    main()

【讨论】:

    【解决方案2】:
    def main():
        # ...
        # <- no return statement
    
    while main():
        # Something
    

    只要条件为真,while 循环就会循环。在这里,由于您的main() 函数没有return 语句,它不会显式地返回任何内容。所以 Python 表现得好像它正在返回 NoneNone 不正确。所以条件是假的,你甚至不会执行一次身体。


    类似的事情怎么样(假设你需要执行main()直到用户想要退出):

    def main():
        # ...
        print("Type 9 to quit")
        choice=input("Select a number:")
        if choice == '9':
            return False
    
        # Handle other cases
        if choice == '1':
            file_create(filename)
        elif choice == '2':
            # ...
    
        return True
    

    另一方面,正如@thiruvenkadam 在下面的评论中所建议的那样,您可以保留您在问题中所写的 main,但是 真的 写一个 infinite循环:

    while True:
        main()
    

    但是那样的话,如果你想优雅地终止你的程序,你将不得不依赖一些其他的机制,比如使用异常......

    【讨论】:

    • 我不太明白你所说的不正确是什么意思。我如何做到这一点
    • 您可以在main() 中使用return True 或在此期间致电main()
    • @anyoneoutre 请花时间再读一遍,并将我的建议main 与您的建议进行比较:如果没有任何return 语句,函数将返回None。如果你想保持你在问题中所写的循环,你将不得不明确地返回True(执行循环体继续循环)或错误的东西如果你想“打破”外部的 while 循环。如果这不是很清楚,我可以建议您花一些时间对 while 循环进行更多试验吗?
    猜你喜欢
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2017-10-12
    • 2020-11-30
    • 2015-05-22
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多