Python while循环允许执行部分代码,直到给定条件返回false为止。也称为预测试循环。可以将其视为重复的if语句。当无涯教程不知道迭代次数时,使用while循环最有效。
语法如下。
while expression: statements
在这里,语句可以是单个语句或一组语句。该表达式应该是任何有效的Python表达式,结果为true或false。 true为任何非零值,false为0。
可以使用循环控制语句更改 循环执行的正常顺序。当while循环的执行完成时,将删除该作用域中定义的所有自动对象。 Python提供了以下在while循环中使用的控制语句。
1. continue - 遇到继续语句时,控件将转移到循环的开头。
# prints all letters except 'a' and 't'
i = 0
str1 = 'learnfk'
while i < len(str1):
if str1[i] == 'a' or str1[i] == 't':
i += 1
continue
print('Current Letter :', str1[i])
i += 1
输出:
Current Letter : l Current Letter : e Current Letter : a Current Letter : n Current Letter : f Current Letter : k
2. Break语句 - 遇到break语句时,它将控制带出循环。
# The control transfer is transfered # when break statement soon it sees t i = 0 str1 = 'learnfk' while i < len(str1): if str1[i] == 'r': i += 1 break print('Current Letter :', str1[i]) i += 1
输出:
Current Letter : l
Current Letter : e
Current Letter : a
3. Pass语句 - pass语句用于声明空循环。它还用于定义空的类,函数和控制语句。
# An empty loop str1 = 'learnfk' i = 0 while i < len(str1): i += 1 pass print('Value of i :', i)
输出:
Value of i : 7
输出:
1 2 3 4 5 6 7 8 9 10
i=1 number=0 b=9 number = int(input("Enter the number:")) while i<=10: print("%d X %d = %d \n"%(number,i,number*i)) i = i+1
输出:
Enter the number:10 10 X 1 = 10 10 X 2 = 20 10 X 3 = 30 10 X 4 = 40 10 X 5 = 50 10 X 6 = 60 10 X 7 = 70 10 X 8 = 80 10 X 9 = 90 10 X 10 = 100
如果在while循环中给出的条件永远不会变为假,则while循环将永远不会终止,并且会变成无限while循环。
while循环中的任何非零值表示始终为真(true)条件,而零则表示始终为假条件。如果希望程序在循环中连续运行而不会受到任何干扰,则方法很有用。
输出:
Hi! we are inside the infinite while loop Hi! we are inside the infinite while loop
var = 1 while(var != 2): i = int(input("Enter the number:")) print("Entered value is %d"%(i))
输出:
Enter the number:10 Entered value is 10 Enter the number:10 Entered value is 10 Enter the number:10 Entered value is 10 Infinite time
Python允许在while循环中使用else语句。当while语句中给定的条件为false时,将执行else块。与for循环类似,如果使用break语句中断了while循环,则else块将不被执行,else块之后的语句将被执行。 else语句与while循环一起使用是可选的。考虑以下示例。
输出:
1 2
在上面的代码中,当遇到break语句时,while循环停止执行并跳过else语句。
terms = int(input("Enter the terms ")) # 前两个初始项 a = 0 b = 1 count = 0 # 检查terms是否为零或负数 if (terms <= 0): print("Please enter a valid integer") elif (terms == 1): print("Fibonacci sequence upto",limit,":") print(a) else: print("Fibonacci sequence:") while (count < terms) : print(a, end = ' ') c = a + b # updateing values a = b b = c count += 1
输出:
Enter the terms 10 Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Python实战 · 从0到1搭建直播视频平台 -〔Barry〕