
迭代意味着反复执行同一个代码块,可能是多次。Python 的while语句被用来构造循环。
在Python中,只要测试条件)为 "True",就用while循环来迭代代码块。只要条件为True,while 循环就用于执行这组语句。while 循环告诉计算机,只要条件得到满足或保持True,就做某件事。
Python While Not in
Python中的while not 循环重复执行循环的主体,直到满足循环终止的条件。使用语法 while not condition,条件为布尔表达式,在条件评估为False 时执行循环主体。
while not的例子
data = 5
while not (data == 0) :
print(data)
data = data - 1
输出
5
4
3
2
1
你可以使用语法**"while variable not in"**iterable来执行循环的主体,如果该变量不是可重复的。
listA = [1, 2, 3]
while 7 not in listA:
listA.append(len(listA) + 1)
print(listA)
输出
1, 2, 3, 4, 5, 6, 7]
Python break 和 continue 语句
Pythonbreak 语句立即完全终止一个循环。Pythoncontinue语句立即终止当前循环的迭代。
Python while else 子句
Python 在 while 循环的结尾让出了一个可选的 else 子句。这是Python的一个新特性,在大多数其它编程语言中都没有。
语法
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
在else子句中指定的**<additional_statement(s)>**将在while循环结束时被执行。
这就是Python中的while不循环。
请参见
The postHow to Use While Not in Pythonappeared first onAppDividend.