for loop

  1. magicians = ['alice', 'david', 'carolina']
  2. for magician in magicians:
  3. print(f"{magician.title()}, that was a great trick!")
  4. print(f"I can't wait to see your next trick, {magician.title()}.\n")
  5. print("Thank you, everyone. That was a great magic show!")

缩进的空格数量可以是任意的,只需前后保持一致就行

numerical lists

range()

  1. # 1,2,3,4
  2. for value in range(1, 5):
  3. print(value)
  4. # 0,1,2,3,4
  5. for value in range(5):
  6. print(value)

用list()函数将range结果转换为list

  1. numbers = list(range(2, 5))
  2. print(numbers)

设置步长

  1. even_numbers = list(range(2, 11, 2))
  2. print(even_numbers)
  3. # 2, 4, 6, 8, 10

数学统计

  1. >>> digits = [1,2,3,4,5,6,7,8,9]
  2. >>> min(digits)
  3. 1
  4. >>> max(digits)
  5. 9
  6. >>> sum(digits)
  7. 45

list comprehensions

  1. squares = [value ** 2 for value in range(1, 11)]
  2. print(squares)
  3. # 等价于
  4. squares = []
  5. for value in range(1, 11):
  6. squares.append(value ** 2)

Working with Part of a List

slice

  1. fruits = ['apple', 'banana', 'orange', 'pineapple', 'pear', 'plum']
  2. print(fruits[1:4]) # index 1, 2, 3
  3. print(fruits[2:]) # index 2到最后
  4. print(fruits[:4]) # index 0到3
  5. print(fruits[-3:]) # 最后3个
  6. print(fruits[1:4:2]) # 第三个参数为步长,默认为1 index 1, 3
  7. print(fruits[-3::-1]) # 步长为负数则反向 ['pineapple', 'orange', 'banana', 'apple']
  8. print(fruits[:]) # 复制整个list

Tuples元组

元组不可修改 an immutable list is called a tuple
image.png
如果声明只有一个值的tuple,需要加逗号

  1. my_t = (1,)
  2. print(my_t[0])

Styling Your Code

  • 用4个空格缩进
  • 每行不超过79个字符
  • 不要过度使用空行

Python Enhancement Proposal (PEP)