Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:;否则";在while循环中_Python_While Loop - Fatal编程技术网

Python:;否则";在while循环中

Python:;否则";在while循环中,python,while-loop,Python,While Loop,我的问题是为什么在while循环中会有“else”子句。例如,我的代码如下所示: a = 100 turns = 0 while a > 0: if func(a, b): #Function returns boolean value a -= 1 turns += 1 else: a -= 2 turns += 1 else: print(turns) 问题是,这与下面的语法有什么不同 a = 1

我的问题是为什么在while循环中会有“else”子句。例如,我的代码如下所示:

a = 100
turns = 0
while a > 0:
    if func(a, b): #Function returns boolean value
        a -= 1
        turns += 1
    else:
        a -= 2
        turns += 1
else:
    print(turns)
问题是,这与下面的语法有什么不同

a = 100
turns = 0
while a > 0:
    if func(a, b): #Function returns boolean value
        a -= 1
        turns += 1
    else:
        a -= 2
        turns += 1
print(turns)

不同之处在于它如何处理循环的异常退出,例如
中断

while True:
    break
else:
    print("not printed")
print("printed")
这同样适用于在循环体内部引发的异常