繁体   English   中英

打破循环?

[英]breaking out of the loop?

我在打破这些循环时遇到了一些麻烦:

done = False
while not done:
    while True:
        print("Hello driver. You are travelling at 100km/h. Please enter the current time:")
        starttime = input("")
        try:
            stime = int(starttime)
            break
        except ValueError:
            print("Please enter a number!")
    x = len(starttime)
    while True:
        if x < 4:
            print("Your input time is smaller than 4-digits. Please enter a proper time.")
            break
        if x > 4:
            print("Your input time is greater than 4-digits. Please enter a proper time.")
            break
        else:
            break

它可以识别数字是<4还是> 4,但是即使输入的数字是4位数字长,它也可以返回到程序的开始,而不是继续到下一个代码段(此处未显示)。

它“返回程序的开始”的原因是因为您将while循环嵌套在while循环内。 break语句非常简单:它结束了程序当前正在执行的(for或while)循环。 这与该特定循环范围之外的任何内容无关。 在嵌套循环内调用break将不可避免地在同一点结束。

如果您要结束任何特定代码块中的所有执行,而无论嵌套的深度如何(并且所遇到的是深层嵌套代码问题的征兆),都应将该代码移入一个单独的功能。 此时,您可以使用return结束整个方法。

这是一个例子:

def breakNestedWhile():
    while (True):
        while (True):
            print("This only prints once.")
            return

所有这些都是基于这样的事实:没有真正的理由让您按照上面的方式进行操作-嵌套while循环几乎从来都不是一个好主意,因为您有两个条件相同的while循环,这似乎毫无意义,并且您已经完成了一个布尔标志,您永远都不会使用它。 如果您实际上在嵌套的whiles中将done设置为True,则中断后,父while循环将不会执行。

您显然想要将done变量用作标志。 因此,您必须在上次休息之前(完成后)进行设置。

...
else:
  done = 1
  break

input()可以采用可选的提示字符串。 我在这里尝试了一些清理流程,希望对您有所帮助。

x = 0
print("Hello driver. You are travelling at 100km/h.")
while x != 4:
    starttime = input("Please enter the current time: ")
    try:
        stime = int(starttime)   
        x = len(starttime)
        if x != 4:
            print("You input ({}) digits, 4-digits are required. Please enter a proper time.".format(x))                 
    except ValueError:
        print("Please enter a number!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM