While循环
for循环用于针对集合中的每个元素都执行一个代码段。
while循环则不断地运行,一直到指定的条件不满足为止。
1 while 语法
while active_condition_val:
do some thing
while active_condition_val:
do some thing
if conditional_val:
break
while active_condion_val:
if condition_val:
continue
do some thing
2. while 例子
输入数字
# -*- coding" utf-8 -*-
message = 'Please enter the numer: '
message += '(Enter \'-1\' when your are finished.)'
while True:
num = input(message)
num = int(num)
if -1 == num:
break
print(num)
其代码输出结果如下:
Please enter the numer: (Enter '-1' when your are finished.)1
1
Please enter the numer: (Enter '-1' when your are finished.)2
2
Please enter the numer: (Enter '-1' when your are finished.)3
3
Please enter the numer: (Enter '-1' when your are finished.)4
4
Please enter the numer: (Enter '-1' when your are finished.)5
5
Please enter the numer: (Enter '-1' when your are finished.)-1
------------------
(program exited with code: 0)
打印奇数
index=0
while index < 10:
index = index+1
if index%2==0:
continue
print(index)
其输出结果如下:
1
3
5
7
9
------------------
(program exited with code: 0)
处理列表
stus=['Alice', 'Bob', 'Cedar']
peoples=[]
print(stus)
print(peoples)
while stus:
stu=stus.pop();
peoples.append(stu)
print(stus)
print(peoples)
其输出结果如下:
['Alice', 'Bob', 'Cedar']
[]
[]
['Cedar', 'Bob', 'Alice']
------------------
(program exited with code: 0)
删除列表中的元素
stus=['Alice', 'Bob', 'Cedar', 'Bob', 'Joe']
print(stus)
while 'Bob' in stus:
stus.remove('Bob')
print(stus)
其输出结果如下:
['Alice', 'Bob', 'Cedar', 'Bob', 'Joe']
['Alice', 'Cedar', 'Joe']
------------------
(program exited with code: 0)
浙公网安备 33010602011771号