摆脱循环?
我遇到一些麻烦打破这些循环:摆脱循环?
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循环具有相同的条件,这似乎毫无意义,并且你已经有了一个布尔标志,完成了,这是你永远不会用到的。如果你实际上在嵌套while循环中设置了True,那么parent while循环在你破解之后不会执行。
为什么你有真正的parens? – 2014-10-29 01:50:58
啊,坏习惯 - 有时C#语法会滑过。 – furkle 2014-10-29 01:51:40
您显然希望使用变量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!")
您在哪里更改为True? – 2014-10-29 01:53:16
尝试: stime = int(starttime)#你的意思是starttime = int(starttime)。 – Crispy 2014-10-29 01:57:57