遍历列表:
nums = ['1','2','3','4']
for num in nums:
print(num)
>for后面,没有缩进的代码,只执行一次,不会重复执行。
会显示错误:IndentationError: expected an indented block
修改为:
nums = ['1','2','3','4']
for num in nums: >for循环,从nums列表中逐次取出一个元素放入num中并输出,直至nums列表中无元素存在
print(num) >此行缩进才可
>>>1 2 3 4
创建数值列表:
range()函数
for value in range(1,5):
print(value) >>>1 2 3 4 不包含5
使用list()可将range()的结果直接转换成列表
nums = list(range(1,6))
print(nums) >>>[1,2,3,4,5]
nums = list(range(2,11,2))
print(nums) >>>取2到11之间的偶数,不断加2
square.py >输出前10个整数的平方加入一个列表中
squares = []
for value in range(1,11): 不要丢掉冒号(:)
square = value**2
squares.append(square)
print(squares)
对数字列表进行简单的统计运算(求最大值、最小值、求和)
digits = [1,2,3,4]
min(digits)
digits = [1,2,3,4]
max(digits)
digits = [1,2,3,4]
sum(digits)
列表解析:
squares = [value**2 for value in range(1,11)]
print(squares)
切片:
bicycles[0:3] bicycles[0:] bicycles[:3] bicycles[:]
遍历切片:
for car in cars[:]:
print(car)
复制列表:
a_cars = cars[:] >不能写成 a_cars = cars
元组: >不可变的列表,使用圆括号而不是方括号
dimensions = (200,50)
遍历元组中的所有值(方法类似列表的操作)
元组的元素不能修改,但是可以给元组的变量赋值
dimensions = (200,50)
dimensions = (400,100)
代码格式相关:
1,易于阅读
2,每级缩进使用四个空格,提升可读性。(避免使用制表符和空格混用)
3,行长:每行不超过80字符,注释不超过72字符
课后题:
# 4-1 遍历列表 pizzas = ['a','b','c'] for pizza in pizzas: print("I Like " + pizza + "!") print("I Really Love Pizza!") # 4-2 动物 pets = ['cat','dog','pig'] for pet in pets: print("A"+ pet +"would make a great pet") print("Any of these animals would make a great pet !") # 4-3 打印数字 1-20 for i in range(1,21): print(i) # 4-4 练习Ctrl +C 来停止执行 # 4-5 计算1-100001的总和 a = [] for i in range(1,100001): a.append(i) print(min(a)) print(max(a)) print(sum(a)) # 4-6 打印 1-20的奇数 for i in range(1,21,2): print(i) # 4-7 打印3的倍数 for i in range(3,31,3): print(i) # 4-8 打印1-10整数的立方 nums = [] for i in range(1,11): nums.append(i**3) print(nums) for num in nums: print(num) # 4-9 将上面的列表,进行解析 nums = [i**3 for i in range(1,11)] for num in nums: print(num) # 4-10 列表切片 nums = [i**3 for i in range(1,11)] print(nums) print("The first three items in the list are : " + str(nums[0:3])) print("Three items from the middle of the list are : " + str(nums[3:6])) print("The three items in the last are : " + str(nums[7:11])) # 4-11 pizzas = ['a','b','c'] friend_pizzas = ['a','b','c'] friend_pizzas.append('d') print(friend_pizzas) pizzas.insert(3,'f') print(pizzas) print("My favorite pizzas are: ") for pizza in pizzas: print(pizza) print("My friend's favorite pizzas are: ") for friend_pizza in friend_pizzas: print(friend_pizza) # 4-12 元组初步 foods = ('a','b','c','d','f') for food in foods: print(food) # foods[0] = tf print(foods) foods = ('a','b','c','j','k') for food in foods: print(food)