Python:for循环练习
程序员文章站
2022-03-21 17:06:14
...
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: