for 循环

1. for i in range() 循环:

for 循环: 已知循环次数的情况下, 需要多次重复代码块时使用

while 循环: 终止条件决定何时停止

range 控制循环次数,range(start,stop, step)

for i in range(6): -- stop = 6 

print(i) --- 0,1,2,3,4,5

for i in range(20, 25):

print(i) -- 20,21,22,23,24

for i in range(50, 0, -10):

print(i) -- 50, 40, 30, 20, 10 

作为循环固定次用法:

for i in range(3):

      sum += number

return sum 

2. range(len()) 用在list  (is better expressed with enumerate)

list = ['a', 'b', 'c']

for i in list:

      print(i) ---- a b c

等同于

list = ['a', 'b', 'c']

for i in range(len(list)):

     print(list[i]) ---- a b c

this is useful when you want to modify the list at certain positions

i.e. 

list = ['a', 'b', 'c', 'd', 'e']

for i in range(len(list)):

     if list[i] in 'aeiou':

        list[i] = 'vowel'

      else:

         list[i] = 'consonant'

list == ['vowel' 'consonant', 'consonant', 'consonant', 'vowel']

for i in range() iterates through numbers. For element in list iterates through whatever is in the list. for i in range(len(list)) iterates through numbers which can be used for index access of list. 

3. for in list 循环

words = ['a', 'b', 'c']

for i in words:

     print(i) -- a b c

列表和其它的“序列”数据类型 比如 strings以及tuples(元组)都常常被用于循环,因为他们有“可被迭代”的特性。你可以组合这些数据结构与range()协同,去在列表中增加项目

for i in range(len(words)):

     words.append('d')

print(words)---a,b,c,d,d,d

此处将'd'作为占位字符串,在words列表中增加了len(words)次'd'(len(words)为起始时words列表中项目的总数/列表原长)

for循环构建一个列表:

list = []

for i in range(3):

      list.append(i)

print(list) - []

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值