1. 让代码既可以被导入又可以被执行。

    2. 用下面的方式判断逻辑“真”或“假”。

      1. if not x:

      的代码:

      1. name = 'jackfrued'
      2. fruits = ['apple', 'orange', 'grape']
      3. owners = {'1001': '骆昊', '1002': '王大锤'}
      4. if name and fruits and owners:
      5. print('I love fruits!')

      不好的代码:

      1. name = 'jackfrued'
      2. fruits = ['apple', 'orange', 'grape']
      3. owners = {'1001': '骆昊', '1002': '王大锤'}
      4. if name != '' and len(fruits) > 0 and owners != {}:
      5. print('I love fruits!')
    3. 善于使用in运算符。

      1. if x in items: # 包含
      2. for x in items: # 迭代

      的代码:

      1. name = 'Hao LUO'
      2. if 'L' in name:
      3. print('The name has an L in it.')

      不好的代码:

    4. 不使用临时变量交换两个值。

      1. a, b = b, a
    5. 的代码:

      1. name = ''.join(chars)
      2. print(name) # jackfrued

      不好的代码:

      1. name = ''
      2. for char in chars:
      3. name += char
      4. print(name) # jackfrued
    6. EAFP优于LBYL。

      EAFP - Easier to Ask Forgiveness than Permission.

      LBYL - Look Before You Leap.

      的代码:

      1. d = {'x': '5'}
      2. try:
      3. value = int(d['x'])
      4. print(value)
      5. except (KeyError, TypeError, ValueError):
      6. value = None

      不好的代码:

      1. d = {'x': '5'}
      2. if 'x' in d and isinstance(d['x'], str) \
      3. and d['x'].isdigit():
      4. value = int(d['x'])
      5. print(value)
      6. else:
      7. value = None
    7. 使用enumerate进行迭代。

      不好的代码:

      1. fruits = ['orange', 'grape', 'pitaya', 'blueberry']
      2. for fruit in fruits:
      3. index += 1
    8. 用生成式生成列表。

      的代码:

      1. data = [7, 20, 3, 15, 11]
      2. result = [num * 3 for num in data if num > 10]
      3. print(result) # [60, 45, 33]

      不好的代码:

      1. data = [7, 20, 3, 15, 11]
      2. result = []
      3. for i in data:
      4. if i > 10:
      5. result.append(i * 3)
      6. print(result) # [60, 45, 33]
    9. 用zip组合键和值来创建字典。

      的代码:

      1. keys = ['1001', '1002', '1003']
      2. values = ['骆昊', '王大锤', '白元芳']
      3. d = dict(zip(keys, values))
      4. print(d)

      不好的代码:

      1. keys = ['1001', '1002', '1003']
      2. values = ['骆昊', '王大锤', '白元芳']
      3. d = {}
      4. for i, key in enumerate(keys):
      5. d[key] = values[i]