1.方法for循环研究
循环是计算机自动完成重复工作的常见方式之一。
例如:
输入
magicians=['alice','davide','carolina']for magician in magicians: print(magician)
输出
alicedavidecarolina
其中(for magician in magicians:)这行代码让python获取列表magicians中的第一个值('alice'),并将其存储到变量magician中。
print(magician)
让python打印magician的值,依然是'alice'。因为其中还包含其他值,python返回到循环的第一行(for magician in magicians:)这行代码,python获取列表中的下一个名字‘davide’,将其存储到变量magician中,再次执行打印 print(magician)代码。
1.2在for循环中执行更多操作
在for循环中,可对每个元素执行任何操作,例如
输入
magicians=['alice','davide','carolina']for magician in magicians: print(magician.title()+',that was a great trick!') print("I can't wait to see your next trick, "+magician.title()+"." )
输出
Alice,that was a great trick!I can't wait to see your next trick, Alice.Davide,that was a great trick!I can't wait to see your next trick, Davide.Carolina,that was a great trick!I can't wait to see your next trick, Carolina.
在for循环中,想包含多少代码都可以。在代码(for magician in magicians:)后面,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。因此,可对列表中的每个值执行任意次数的操作。
如果忘记进行缩进,就会出现如下情况
magicians=['alice','davide','carolina']for magician in magicians: print(magician.title()+',that was a great trick!')print("I can't wait to see your next trick, "+magician.title()+"." )#首行未进行缩进
输出
Alice,that was a great trick!Davide,that was a great trick!Carolina,that was a great trick!I can't wait to see your next trick, Carolina.
首行不缩进列表循环完毕,执行最后一次的值。打印出的结果就是如下。
(Carolina,that was a great trick!
I can't wait to see your next trick, Carolina.)
2.创建数字列表
列表非常适合用于存储数字集合,而python提供了很多工具,可帮助我们高效地处理数字列表。
2.1使用函数range()
输入
for value in range (1,5): print(value)
输出
1234
在这个事例中,range()只是打印1~4,这是在编程语言中经常看到的差一行为的结果。函数range()让python从你指定的第一个数值开始,(我指定的第一个数字是1)并在到达你指定的第二个值后停止,因此输出不包含第二个值(这里为5).
2.2使用range()创建数字列表
要创建数字列表,可使用函数list(0将range()的结果直接转换为列表。如果将range()作为list()的参数,输出将为一个数字列表。
输入
number=list(range(1,6))print(number)ji_number=list(range(1,6,2))#从1开始加2print(ji_number)ou_number=list(range(2,6,2))#从2开始加2print(ou_number)
输出
[1, 2, 3, 4, 5][1, 3, 5][2, 4]
在这行代码中(ji_number=list(range(1,6,2))#从1开始加2)到6为止。
还可表示1~10的乘方运算
输入
squares=[]for value in range(1,11): square=value**2 squares.append(square)#将suquare中循环值添加进入squares列表中print(squares)
输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2.3列表解析
输入
squares=[value**2 for value in range(1,11)]print(squares)
输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]