Python中用while语句和for语句表示循环执行某一段代码
while后面跟一个条件,或者跟一个序列(列表、元组等),序列为空则跳出循环,否则继续循环
for循环后面跟一个序列,循环次数为序列的长度
while循环可以加个else语句,跳出while的时候就执行这个else
输出: 3 2 1
shoplist = ['apple', 'mango', 'carrot', 'banana'] while shoplist: print(3)输出:一直输出3,直到按ctrl+c
shoplist = ['apple', 'mango', 'carrot', 'banana'] while shoplist: print(3) shoplist = shoplist[:(len(shoplist)-1)]#每次循环都去掉最后一个元素输出: 3 3 3 3
shoplist = ['apple', 'mango', 'carrot', 'banana'] while shoplist: print(3) shoplist = shoplist[:(len(shoplist)-1)] else: print('finished')#else语句输出: 3 3 3 3 finished
shoplist = ['apple', 'mango', 'carrot', 'banana'] for i in shoplist: print(i) #这里面i会被逐次赋值为shoplist里面的元素输出: apple mango carrot banana
shoplist = ('apple', 'mango', 'carrot', 'banana') for i in shoplist: print(i) #这里shoplist是元组,for循环也可以跟元组输出: apple mango carrot banana