Python:for循环练习

1.引例

magicians = ["alice",'david',"carolina"]
for magician in magicians:	
	print(magician)
	#for循环有‘:’,for循环会执行每个缩进
 	print(magician.title())
 	#该缩进也在for循环里面
print("Thank you,That was a great magic show!")

answer:
在这里插入图片描述
2. list()——将结果直接转换成列表
range(参数1,参数2)——python从指定的第一个参数开始数,并在到达所指定的第二个参数后停止

for value in range(1,6):	
	print(value)

answer:
在这里插入图片描述
range(参数1,参数2,参数3)——python从指定的第一个参数开始数,每次加上参数3,直到达到或超过参数2

even_numbers = list(range(2,11,2))
print(even_numbers)
#函数rang()从2开始数,不断加2,直到达到或超过终值11

answer:
在这里插入图片描述
3.实例:计算当前值的平方,并将结果储存到变量square中,然后将新计算得到的平方值,附加到列表末尾
方法一:

squares = []
for value in range(1,11):			
	square = value**2	
	squares.append(square)
print(squares)

方法二:

squares = []
for value in range(1,11):	
	squares.append(value**2)
print(squares)

answer:
在这里插入图片描述
4.min(),max()——分别找出数字列表的最大和最小值
sum()——求和

digits = [1,2,3,4,5]
print(min(digits))
#min和max可以分别找出数字列表的最大和最小值
print(sum(digits))
#sum可以得到数字列表的总和

answer:
在这里插入图片描述
5.实例:for循环和创建新元素的代码合并成一行,并自动附加新元素

squares = [value**2 for value in range(1,10)]
print(squares)

answer:
在这里插入图片描述
6.切片

players = ['charles','martina','michael','florence','eli']

print(players[0:3])
#创建切片,指定要使用的第一个元素和最后一个元素
#python在到达指定的第二个索引前面的元素后停止

print(players[:3])
#若没有指定起始索引,python自动从列表开头提取元素

print(players[2:])
#从指定索引到最后一个元素

print(players[-2:])
#负数索引返回离列表末尾相应距离的元素

answer:
在这里插入图片描述
7.实例:for循环遍历切片

players = ['charles','martina','michael','florence','eli']
for player in players[:3]:	
	print(player.title())

answer:
在这里插入图片描述
8.综合练习

my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]

print("My favorite foods are : ")
print(my_foods)

print("\nMy favorite foods are : ")
print(friend_foods)

my_foods.append('cannoli')
friend_foods.append('ice cream')

print("My favorite foods are : ")
print(my_foods)

print("\nMy favorite foods are : ")
print(friend_foods)

answer:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值