如何无限期地使这个程序循环?

时间:2018-01-15 17:30:38

标签: python python-3.x loops infinite-loop

我想从开头到结尾无限地循环这段代码(直到用户杀死它),所以我不必继续重新运行它。反正有可能使这成为可能吗?我非常感谢帮助。程序应该在用户输入“完成”后重新启动(并打印出所有细节。)

print ("Input done when finished")
print ("Input thresholds")

maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))


minimum = None
maximum = None

while True:
    inp =input("Enter a number: ")
    if inp == "done": 
        break

    try:
        num = float(inp)
    except:
        print ("Invalid input")
        continue  

    ## ---- Additional Check ---- ##
    if num > maximumnum:
        print('Number greater the maximum allowed range')
        break

    if num < minimumnum:
    print('Number smaller the maximum allowed range')
    break        
    ## -------------------------- ##                  

    if minimum is None or num < minimum:
        minimum = num

    if maximum is None or num > maximum:
        maximum = num

print ("Maximum:", maximum)
print ("Minimum:", minimum)
print ("Try again")

3 个答案:

答案 0 :(得分:0)

为什么不在True中将整个脚本包装在另一个脚本中?要停止,用户必须终止正在运行的进程。

while True:
    print ("Input done when finished")
    print ("Input thresholds")

    maximumnum = int(input("Input maximum number: "))
    minimumnum = int(input("Input minimum number: "))


    minimum = None
    maximum = None

    while True:
        inp =input("Enter a number: ")
        if inp == "done": 
            break

        try:
            num = float(inp)
        except:
            print ("Invalid input")
            continue  

        ## ---- Additional Check ---- ##
        if num > maximumnum:
            print('Number greater the maximum allowed range')
            break

        if num < minimumnum:
        print('Number smaller the maximum allowed range')
        break        
        ## -------------------------- ##                  

        if minimum is None or num < minimum:
            minimum = num

        if maximum is None or num > maximum:
            maximum = num

    print ("Maximum:", maximum)
    print ("Minimum:", minimum)
    print ("Try again")

答案 1 :(得分:0)

我经常使用这样的范例来完成“循环,直到我说出来” 有点像。

class UserKilledException(KeyboardInterrupt):
     pass

try:
    while True:
        #do stuff
except UserKilledException:
    #do cleanup here

只要用户决定以某种方式关闭应用程序,就让代码抛出UserKilledException。如果它是一个cli应用程序,那么KeyboardInterrupt就可以了。

答案 2 :(得分:0)

我会将它包装在方法上并在无限循环中运行它。请尝试以下方法:

SomeProject = SomeProject
SomeOtherProject = SomeOtherProject
etc.

希望这有帮助。