Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。当然也可以遍历所有的字符串,列表,元祖等。
其基本形式为:
while 判断条件:
执行语句……
执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件假false时,循环结束。
for 循环一般是用在一个有次数的循环上。
while 循环用在有条件的控制上。
来个容易上手的例子:
n = 0 ## 给n赋值初始值 0
while True: ## True为表达式成立
if n == 10: ## 当 n==10的时候
break ## 跳出循环
print n, 'hello' ## 打印 ‘hello’
n += 1 ## n=n+1
## 整体的程序是:使用while循环打印hello,当n==10 的时候就会停止。
执行结果:
0 hello
1 hello
2 hello
3 hello
4 hello
5 hello
6 hello
7 hello
8 hello
9 hello
手动选择停止 while 循环:
while True:
aa = raw_input("pls input anything you want, use 'quit' to stop: ")
if aa == 'quit':
break
输出的结果是:
pls input anything you want, use 'quit' for stop: qawe
pls input anything you want, use 'quit' for stop: 123
pls input anything you want, use 'quit' for stop: q12
pls input anything you want, use 'quit' for stop: quit
Process finished with exit code 0
在 python 中,while … else 在循环条件为 false 时执行 else 语句块:
#!/usr/bin/python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
以上实例输出结果为:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
#!/usr/bin/python
list1 = []
with open('/tmp/asd.txt') as aa:
for i in aa.readlines():
list1.append(i)
line1 = list1[0][0:4] + list1[1][4:9]
line2 = list1[1][0:4] + list1[0][4:9]
with open('/tmp/asd.txt','w') as aa:
aa.write(line1)
aa.write(line2)
dict3 = {'A': 65, 'C': 67, 'B': 66, 'E': 69, 'D': 68, 'G': 71, 'F': 70, 'I': 73, 'H': 72, 'K': 75, 'J': 74, 'M': 77, 'L': 76, 'O': 79, 'N': 78, 'Q': 81, 'P': 80, 'S': 83, 'R': 82, 'U': 85, 'T': 84, 'W': 87, 'V': 86, 'Y': 89, 'X': 88, 'Z': 90, 'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 111, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}
# A 65
# B 66
# ...
# y 121
# z 122
dict2 = sorted(dict3.items(),key=lambda d:d[0])
with open('/tmp/aa.txt','w') as fd:
for k,v in dict2:
fd.write(k + ' ')
fd.write(str(v)+ '\n')