首页 > 编程语言 >【笨方法学python】ex32 - 循环和列表

【笨方法学python】ex32 - 循环和列表

时间:2022-10-08 07:55:25浏览次数:52  
标签:elements 省略 start python stop 计数 ex32 print 方法学

代码如下:

点击查看代码
# coding=utf-8
the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']


# this first kind of for-loop goes through a list
for number in the_count:
    print "This is count %d" % number

# same as above
for fruit in fruits:
    print "A fruit of type: %s" % fruit

# also, we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
    print "I got %r" % i

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print "Adding %d to the list." % i
    # append is a function that lists understand
    elements.append(i)

# now we can print then out too
for i in elements:
    print "Element was: %d" % i

# 语法
# range(start, stop, step)
# 参数名称	    说明	            备注
# start     	计数起始位置	    整数参数,可省略。省略时默认从0开始计数
# stop      	计数终点位置	    不可省略的整数参数。计数迭代的序列中不包含stop
# step      	步长	            可省略的整数参数,默认时步长为1

执行结果:
image

标签:elements,省略,start,python,stop,计数,ex32,print,方法学
From: https://www.cnblogs.com/TiramisuPS/p/16767841.html

相关文章