for语句
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串
for的实现逻辑
for song in songs:
# song = '爱转角' => song[0]
print("正在播放{}".format(song))
# 把索引 + 1
# song = 晴天 ==》 song[1]
实例1:
for i in "python":
print(i,end="") #end="" 表示不换行打印
#打印结果:python
实例2.通过列表方式:
list = ["banana","apple","orage","lenmo"]
for fruit in list:
print("fruit:{}".format(fruit))
#打印结果:fruit:banana
#fruit:apple
#fruit:orage
#fruit:lenmo
列表可以使用 for 循环
元组可以使用 for 循环
字典使用 for 循环,取到的默认是所有 key, 如果想取到所有value:
for i in dic.values():
如果想取到所有的值:
for e in dic.items():
实例1:
dic = {"yello":"banana","red":"apple"}
for i in dic:
print(i) ===> 打印结果:yello red
实例2:
dic = {"yello":"banana","red":"apple"}
for i in dic.values():
print(i) ===> 打印结果:banana apple
实例3:
dic = {"yello":"banana","red":"apple"}
for i in dic.items():
print(i) ===> 打印结果:('yello', 'banana') ('red', 'apple')
实例4:
dic = {"yello":"banana","red":"apple"}
for i in dic:
print(dic[i]) ===> 打印结果:banana apple
实例5:
for key ,value in dic.items():
print("key:{} , value:{}".format(key,value)) ===> 打印结果:key:yello , value:banana key:red , value:apple
for 的嵌套
实例1:
list = ["banana","apple","orage","lenmo"]
dict = ["color","fruit"]
for i in list:
for e in dict:
print("list :{} , dict :{}".format(list,dict))
'''
打印结果:
list :banana , dict :color
list :banana , dict :fruit
list :apple , dict :color
list :apple , dict :fruit
list :orage , dict :color
list :orage , dict :fruit
list :lenmo , dict :color
list :lenmo , dict :fruit
会先执行完 dict 里面的所有元素,在返回执行list里面的下一个元素
'''
实例2:
python = [['yello','banana'],['red','apple'],['orange','orange']]
for i in python:
print(i)
for e in i:
print(e)
'''
打印结果:
['yello', 'banana']
yello
banana
['red', 'apple']
red
apple
['orange', 'orange']
orange
orange
'''
for 常见面试题 :乘法表
方法1:
for i in range(1,10):
for e in range(1,i+1):
print("{} * {} = {}".format(i, e, i * e), end='\t')
print()
方法2:
for i in range(1,10):
for j in range(1, 10):
if j <= i:
print("{} * {} = {}".format(i, j, i*j), end='\t')
print()