while循环:
在编程中,我们常常会用到循环,即便是我们每天使用的程序很有可能就包含while循环。例如,游戏使用while循环,确保在玩家想玩时不断运行,并在玩家想退出时停止运行。
# 注!使用while循环的时候常常要有break存在,不然会出现无限循环# while循环后面跟布尔表达式,为True则循环# while是无限循环,直到满足某一条件退出a = 0while 1: # python中,数字非0即为True a += 1 if a == 5: # continue 跳出此次循环,返回循环开头,继续执行 continue if a == 10: # break 跳出当前的while循环 break print(a)
输出结果
12346789
使用while循环删除包含特定值的列表元素
num_list = [1,2,3,0,4,0,59,0,0,0]# while后面表达式不成立时,则不会进入循环,所以不需要breakwhile 0 in num_list: num_list.remove(0)
输出结果
[1, 2, 3, 4, 59]
使用while循环移动列表中元素至另一个列表
num_list = [1,2,3,4]num2_list = []# num_list不为空则是Truewhile num_list: nums = num_list.pop() num2_list.append(nums)print(num2_list)
输出结果
[4, 3, 2, 1]