标签:end alt int color ima 字典 字符 列表、元组、字典 mil
Python for 循环语句:遍历任何序列的项目,可以是字符串、列表、元组、字典、集合对象。
流程图:
第一种:
‘‘‘
for 迭代对象 in 序列:
代码块(一行语句或多行代码)
‘‘‘
第二种:
‘‘‘
for 迭代对象 in 序列:
代码块(一行语句或多行代码)
else:
代码块(一行语句或多行代码)
‘‘‘
示例:
第一种:
for i in range(4):
print(i)
# 0
# 1
# 2
# 3
# 字符串
strs = "Hello World."
for i in strs:
print(i,end=" ")
# H e l l o W o r l d .
print()
# 列表
lst = [1,2.3,8+9j,‘abc‘,(4,5),{7,8,‘a‘},{‘a‘:4}]
for i in lst:
print(i,end=" ")
# 1 2.3 (8+9j) abc (4, 5) {8, ‘a‘, 7} {‘a‘: 4}
print()
# 元组
tup = (1,2,3,4,5,6)
for i in tup:
print(i,end=" ")
# 1 2 3 4 5 6
print()
# 字典
dic = {‘a‘:{‘b‘:123},(4,5):‘str‘,123:[4,5,6]}
# 键为不可变类型 字符串、元组、数字
for i in dic:
print(i,end=" ")
# a (4, 5) 123
print()
# 集合
set_1 = {1,2.5,‘a‘,(7,8,9)}
for i in set_1:
print(i,end=" ")
# 1 2.5 a (7, 8, 9)
print()
第二种:
for i in range(4):
print(i)
else:
print("运行OK")
# 0
# 1
# 2
# 3
# 运行OK
# 字符串
strs = "Hello World."
for i in strs:
print(i,end=" ")
# H e l l o W o r l d . 运行OK
else:
print("运行OK")
print()
# 列表
lst = [1,2.3,8+9j,‘abc‘,(4,5),{7,8,‘a‘},{‘a‘:4}]
for i in lst:
print(i,end=" ")
# 1 2.3 (8+9j) abc (4, 5) {8, ‘a‘, 7} {‘a‘: 4} 运行OK
else:
print("运行OK")
print()
# 元组
tup = (1,2,3,4,5,6)
for i in tup:
print(i,end=" ")
# 1 2 3 4 5 6 运行OK
else:
print("运行OK")
print()
# 字典
dic = {‘a‘:{‘b‘:123},(4,5):‘str‘,123:[4,5,6]}
# 键为不可变类型 字符串、元组、数字
for i in dic:
print(i,end=" ")
# a (4, 5) 123 运行OK
else:
print("运行OK")
print()
# 集合
set_1 = {1,2.5,‘a‘,(7,8,9)}
for i in set_1:
print(i,end=" ")
# 1 2.5 a (7, 8, 9) 运行OK
else:
print("运行OK")
print()
2020-02-06
标签:end alt int color ima 字典 字符 列表、元组、字典 mil
原文地址:https://www.cnblogs.com/hany-postq473111315/p/12268067.html