08--转圈圈---for循环

PS:由于今日有其他事情,只写精简版的博客,请见谅,后续会进行修改,请忽略括号中的内容。。。(因为被罚写。。。o(╥﹏╥)o)

一。什么是for循环

  循环就是重复做某件事,是python提供的第二种循环机制

二。为什么要有for循环

  理论上for循环可以做的事,while循环都可以做

  之所以用for循环,是因为在循环遍历取值的时候比while循环更加简洁

三。for循环语法

for 变量名 in 可迭代对象:
    代码1
    代码2

四。for 循环基本使用--循环取值

  1、列表循环取值

 l = ['alex_dsb', 'lxx_dsb', 'egon_nb']
 for x in l:  # x='lxx_dsb'
     print(x)

  2、字典循环取值

dic={'k1':111,'k2':2222,'k3':333}
for k in dic:
    print(k,dic[k])

  3、字符串循环取值

msg="you can you up,no can no bb"
for x in msg:
    print(x)

  4、总结for 和 while的异同

1、相同之处:都是循环,for循环可以干的事,while循环也可以干
2、不同之处:
          while循环称之为条件循环,循环次数取决于条件何时变为假
          for循环称之为"取值循环",循环次数取决in后包含的值的个数

五。for循环控制循环次数

for x in 'a c':
    inp_name=input('please input your name:   ')
    inp_pwd=input('please input your password:   ')

# in后直接放一个数据类型来控制循环次数有局限性:
#                 当循环次数过多时,数据类型包含值的格式需要伴随着增加

六。for 循环--range

  1、python2中

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
>>> range(1,9) # 1...8
[1, 2, 3, 4, 5, 6, 7, 8]
>>> 
>>> range(1,9,1) # 1 2 3 4 5 6 7 8 
[1, 2, 3, 4, 5, 6, 7, 8]
>>> range(1,9,2) # 1 3 5 7 
[1, 3, 5, 7]

  2、python3中

  range()在python3里得到的是一只"会下蛋的老母鸡"
>>> range(9)
range(0, 9)
>>>
 3、for + continue
for i in range(6):  # 0 1 2 3 4 5
    if i == 4:
        continue
    print(i)

  4、for+else 与for+break与while循环相同

    补充:终止for循环只能使用break一种方式

 
posted @ 2020-03-10 15:43  微信搜索-程序媛小庄  阅读(201)  评论(0编辑  收藏  举报