Python 打破循环?
我在打破这些循环方面遇到了一些问题:Python 打破循环?,python,loops,Python,Loops,我在打破这些循环方面遇到了一些问题: 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) bre
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
done=False
虽然没有这样做:
尽管如此:
打印(“你好,驾驶员。您正在以100公里/小时的速度行驶。请输入当前时间:”)
开始时间=输入(“”)
尝试:
时间=整数(开始时间)
打破
除值错误外:
打印(“请输入一个数字!”)
x=len(开始时间)
尽管如此:
如果x<4:
打印(“您的输入时间小于4位。请输入正确的时间。”)
打破
如果x>4:
打印(“您的输入时间大于4位。请输入正确的时间。”)
打破
其他:
打破
它可以识别数字是<4还是>4,但即使输入的数字是4位数,它也会返回到程序的开头,而不是继续到下一段代码,这里没有 它“返回到程序开头”的原因是因为您将while循环嵌套在while循环中。break语句非常简单:它结束程序当前执行的(for或while)循环。这与特定循环范围之外的任何内容都没有关系。在嵌套循环中调用break将不可避免地在同一点结束
如果您希望结束任何特定代码块中的所有执行,而不管嵌套的深度有多深(并且您遇到的是深度嵌套代码问题的症状),则应将该代码移动到单独的函数中。此时,可以使用return结束整个方法
下面是一个例子:
def breakNestedWhile():
while (True):
while (True):
print("This only prints once.")
return
所有这一切都是次要的,因为没有真正的理由让你按照上面的方式做事——嵌套while循环几乎从来都不是一个好主意,你有两个while循环,条件相同,这似乎毫无意义,而且你有一个布尔标志,done,你从来不用费心使用它。如果您在嵌套的whiles中将done设置为True,则父while循环在中断后将不会执行。您显然希望使用变量
done
作为标志。因此,你必须在你最后一次休息之前(当你休息完毕时)设置它
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来代替呢?啊,坏习惯——有时C#语法会漏掉。你在哪里把done改为True?试试:stime=int(starttime)#你是说starttime=int(starttime)。
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!")