ex32 for循环

本文通过三个实例详细解析了Python中for循环的使用方法,包括基本的遍历输出、处理复杂类型列表以及使用range和append创建并填充列表的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一个关于for循环的简单练习

the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','bananas']
change = [1,'pennies',2,'dimes',3,'quarters']

#for循环输出
for number in the_count:
    print("The number is %d." %number)
for fruit in fruits:
    print("Do you like %s?" %fruit)
#如果输出列表的包含多种格式,使用%r
for i in change:              #i在这里指的是列表change里面的所有元素
    print("I got %r." %i)

#创建一个空列表,使用range和append将列表元素添加到空列表中去
elements = []                 #空列表
for i in range(0,6):
    print("Adding %d to the list." %i)
    elements.append(i)        #添加0-6的元素到elements中,注意元素顺序是包头不包尾

for i in elements:            #经过append之后,elements现在是[0,1,2,3,4,5]
    print("Elements is %d." %i)

运行结果

PS E:\tonyc\Documents\Vs workspace> cd ‘e:\tonyc\Documents\Vs workspace’; ${env:PYTHONIOENCODING}=‘UTF-8’; ${env:PYTHONUNBUFFERED}=‘1’; & ‘D:\Anboot\Python\python.exe’ ‘c:\Users\tonyc.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\ptvsd_launcher.py’ ‘–default’ ‘–client’ ‘–host’ ‘localhost’ ‘–port’ ‘58107’ ‘e:\tonyc\Documents\Vs workspace\The Hard Way\ex32(for循
环).py’
The number is 1.
The number is 2.
The number is 3.
The number is 4.
The number is 5.
Do you like apples?
Do you like oranges?
Do you like pears?
Do you like bananas?
I got 1.
I got ‘pennies’.
I got 2.
I got ‘dimes’.
I got 3.
I got ‘quarters’.
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Elements is 0.
Elements is 1.
Elements is 2.
Elements is 3.
Elements is 4.
Elements is 5.

思考

  1. range的用法
    range可以对一个列表进行从头到尾的迭代,具体使用格式是range(start:stop,[step]),步长为可选选项
  2. 可以可以直接将 elements 赋值为 range(0,6),而无需使用 for 循
    环,也即
elements = []                 #空列表
for i in range(0,6):

可以写成

elements = range(0,6)                 #空列表
for i in elements:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值