Python学习07: for 语句的介绍和使用

for语句

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串
for循环的语法格式
for的实现逻辑

for song in songs:
# song = '爱转角' => song[0]
print("正在播放{}".format(song))
# 把索引 + 1
# song = 晴天 ==》 song[1]

实例1for 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

实例5for key ,value in dic.items():
    print("key:{} , value:{}".format(key,value))    ===> 打印结果:key:yello , value:banana    key:red , value:apple

for 的嵌套

实例1list = ["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 常见面试题 :乘法表

方法1for i in range(1,10):
    for e in range(1,i+1):
        print("{} * {} = {}".format(i, e, i * e), end='\t')
    print()


方法2for i in range(1,10):
    for j in range(1, 10):
        if j <= i:
            print("{} * {} = {}".format(i, j, i*j), end='\t')
    print()
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值