for 循环,又名:遍历循环
while 循环,又名:条件循环
# 死循环 显示*,下面运算也都是*,但只是在等待上面的死循环结束
#解决方法 点击interrupt kernel符号,或者点击Kernel --Interrupt/Restart
costs = [3,4,8,14,34,67,100]
for cost in costs:
print('消费 {} 元'.format(cost))
消费 3 元 消费 4 元 消费 8 元 消费 14 元 消费 34 元 消费 67 元 消费 100 元 costs = [3,4,8,14,34,67,100] for cost in costs: print('消费{}元'.format(str(cost).center(10))) #加入样式,打印出来美观
消费 3 元 消费 4 元 消费 8 元 消费 14 元 消费 34 元 消费 67 元 消费 100 元
生成一个长度为20的随机列表 import random random_numbers = [] while len(random_numbers) < 20: random_numbers.append(random.randint(1,10)) #限定范围1`10 print(random_numbers,len(random_numbers)) [10, 1, 3, 7, 3, 6, 8, 8, 10, 1, 8, 6, 2, 1, 6, 6, 5, 5, 9, 7] 20
编程建议:只要能使用for循环,就不要使用while循环
因为条件复杂时,while循环易写成死循环,则跳不出来
random_number = [ ]
for i in range(20):
random_numbers.append(random.randint(1,10)) #限定范围1`10
print(random_numbers,len(random_numbers))
[10, 10, 1, 4, 5, 9, 8, 6, 4, 10, 8, 9, 7, 6, 2, 6, 8, 1, 1, 10] 20
必须用while循环的情况:当循环的条件与数量无关系时,只能用while循环
题目:往空列表添加随机数,直到添加的数为9,则终止
random_numbers = []
while 9 not in random_numbers:
random_numbers.append(random.randint(1,10))
print(random_numbers,len(random_numbers))
[10, 5, 2, 1, 7, 1, 8, 9] 8
问题: a = [1,2,3], b = 1, c = b in a,猜测一下,c是一个什么类型,是否是一个元组?
是否是一个元组?
重点:只有一个元素的列表
问题: a = [1,2,3], b = 1, c = b in a,猜测一下,c是一个什么类型,是否是一个元组?
In [1]:a = [ ]
b = ()
type(a),type(b)
Out[1]: (list, tuple)
In [2]:a = [1 ]
b = (1) #原来为空的元组,加入1,变为元组中实际的值,b变为int型(元组只要不为空,则就为True)
type(a),type(b)
Out[2]: (list, int)
# b = (1,) 加入',' 则变为包含一个元素的元组
In [3]:a = [1]
b = (1,)
type(a),type(b),b,len(b)
Out[13]:(list, tuple, (1,), 1)