码迷,mamicode.com
首页 > 其他好文 > 详细

控制流程-for循环

时间:2020-02-04 18:42:57      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:支持   for   for循环   ems   使用   div   hello   mil   字符   

1:for 循环的使用

#语法:
for i in XXX:
    # 循环体
2:for 循环的案例
"""需求:1、计算1+2+3+4+。。。。100的结果"""
s = 0
for i in range(1, 101):
    s = s +i
print(s)


"""
需求二:使用for打印100遍hello python
需求三:打印到第50遍之后 后面的不再打印
"""
#for循环也支持使用break,continue

for i in range(100):
    print("这是第{}遍打印:hello python".format(i + 1))
    if i + 1 == 50:
        continue
    print("------------end:{}----------------".format(i+1))

3:for 循环的应用场景
# 遍历字符串
s = "fghjkldd"
for i in s:
    print(i)

# 遍历元组
tu = (11, 22, 3, 33, 4)
for item in tu:
    print(item)

# 遍历列表
li = [11, 22, 33, 4, 5, 2, 5, 2]
for i in li:
    print(i)

# 字典的遍历
dic = {"name": "musne", "age": 18, "gender": "nan"}

# 直接遍历字典:遍历出来的是字典的键
for i in dic:
     print(i)

# 遍历字典中元素的值:values
for i in dic.values():
     print(i)

# 同时遍历字典的键和值:items
# 遍历出来的是一个包含键和值的元组
for i in dic.items():
    print(i)

 

 
 

控制流程-for循环

标签:支持   for   for循环   ems   使用   div   hello   mil   字符   

原文地址:https://www.cnblogs.com/liyuna/p/12260362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!