网络知识 娱乐 python——for和while循环遍历四大容器

python——for和while循环遍历四大容器

python——for和while循环遍历四大容器

# 定义列表nlist1 = [100, 'hello', True, 12.5, (10, 20) ]nfor value in list1:n print(value)nn# 定义元组ntuple1 = (10, 20, 30, 40, 50)nfor i in tuple1:n print(i)nn# 定义字符串nstr1 = 'hello'nfor i in str1:n print(i)nn# 定义字典ndict1 = {"name": "s李白", "age": 30, "high": 178.5}nfor k in dict1:n print(k, dict1[k])nn# 注意:for循环只能遍历像列表,元组,字符串,字典这样的可以遍历的容器,n# 不能遍历数字,浮点数,布尔类型这样不可遍历的数据

while循环基本使用

示例:使用while循环实现5次你好

#定义变量记录循环次数n#while后面添加条件判断n#while条件满足时,执行缩进部分代码n#改变循环变量便于下次循环ßncount = 1nwhile( count <= 5)n print('你好 ,count = %d' %count)n count += 1

while循环遍历容器

list1 = [100, 'hello', True, 12.3, (10, 20)]ni = 0nwhile i < len(list1):n print('list1[%d] = %s' % (i, list1[i]))n i += 1