[Top] Python Development Series Courses (17) - Python "Conventions"

Python "conventions"

The word "custom" refers to "customary practice, conventional method, consistent practice", and the English word corresponding to this word is "idiom". Since Python has significant differences in syntax and usage from many other programming languages, as a Python developer, if you can't master these conventions, you can't write "Pythonic" code. Below we summarize some code idiomatic in Python development.

  1. Make code both importable and executable.

    if __name__ == '__main__':

  2. The logical "true" or "false" is judged in the following way.

    if x:
    if not x:
True False
non-empty string empty string
Value is not 0 value 0
non-empty container (length greater than 0) empty container (length 0)
None
True False

3. Be good at using the in operator.

Python
if x in items: # 包含
for x in items: # 迭代

Good code:

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

Bad code:

Python
name = 'Hao LUO'
if name.find('L') != -1:
print('This name has an L in it!')

  1. Swap two values ​​without using a temporary variable.

    a, b = b, a
  2. Build strings from sequences.

    Good code:

    chars = ['j', 'a', 'c', 'k', 'f', 'r', 'u', 'e', 'd']
    name = ''.join(chars)
    print(name)  # jackfrued

    Bad code:

    chars = ['j', 'a', 'c', 'k', 'f', 'r', 'u', 'e', 'd']
    name = ''
    for char in chars:
       name += char
    print(name)  # jackfrued
  3. EAFP is better than LBYL.

    EAFP - **E**asier to **A**sk **F**orgiveness than **P**ermission.

    LBYL - **L**ook **B**efore **Y**ou **L**eap.

    Good code:

    d = {'x': '5'}
    try:
    value = int(d['x'])
    print(value)
    except (KeyError, TypeError, ValueError):
    value = None

    Bad code:

    d = {'x': '5'}
    if 'x' in d and isinstance(d['x'], str) \
        and d['x'].isdigit():
    value = int(d['x'])
    print(value)
    else:
    value = None
  4. Use enumerate to iterate.

    Good code:

    fruits = ['orange', 'grape', 'pitaya', 'blueberry']
    for index, fruit in enumerate(fruits):
    print(index, ':', fruit)

    Bad code:

    fruits = ['orange', 'grape', 'pitaya', 'blueberry']
    index = 0
    for fruit in fruits:
    print(index, ':', fruit)
    index += 1
  5. Generate lists with production expressions.

    Good code:

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

    Bad code:

    data = [7, 20, 3, 15, 11]
    result = []
    for i in data:
    if i > 10:
        result.append(i * 3)
    print(result)  # [60, 45, 33]
  6. Combine keys and values ​​with zip to create a dictionary.

    Good code:

    keys = ['1001', '1002', '1003']
    values = ['骆昊', '王大锤', '白元芳']
    d = dict(zip(keys, values))
    print(d)  
    
    # {'1001': '骆昊', '1002': '王大锤', '1003': '白元芳'}
    

    Bad code:

    keys = ['1001', '1002', '1003']
    values = ['骆昊', '王大锤', '白元芳']
    d = {}
    for i, key in enumerate(keys):
    d[key] = values[i]
    print(d)
    
    # {'1001': '骆昊', '1002': '王大锤', '1003': '白元芳'}
    

Note : The content of this article comes from the Internet, and interested readers can read the original text ."

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324872338&siteId=291194637