This is the 17th day of my participation in the August Challenge

In this series of reading notes for Effective Python (2nd edition), chapter 1 teaches Pythonic thinking.

Query the Python version you use

import sys
print(sys.version_info)
print(sys.version)
Copy the code

Article 2 follows the PEP 8 Style guide

pylint

Learn the difference between bytes and STR

slightly

Item 4 replaces the C-style format string and str.format method with an f-string that supports interpolation

pantry = [
    ('avocados'.1.25),
    ('bananas'.2.5),
    ('cherries'.15),]for i, (item, count) in enumerate(pantry):
    print(f'#{i+1}: '
          f'{item.title():<10s} = '
          f'{round(count)}')

places = 3
number = 1.23456
print(f'My number is {number:.{places}f}')
Copy the code

Article 5 replaces complex expressions with auxiliary functions

def get_first_int(values, key, default=0) :
    found = values.get(key, [' '])
    if found[0] :return int(found[0])
    return default

green = get_first_int(my_values, 'green')
print(f'Green:   {green! r}')
Copy the code

6. Split data structures directly into multiple variables, not subscripts

snacks = [('bacon'.350), ('donut'.240), ('muffin'.190)]
for i in range(len(snacks)):
   item = snacks[i]
   name = item[0]
   calories = item[1]
   print(f'#{i+1}: {name} has {calories} calories')

for rank, (name, calories) in enumerate(snacks, 1) :print(f'#{rank}: {name} has {calories} calories')
Copy the code

Use enumerate instead of range

flavor_list = ['vanilla'.'chocolate'.'pecan'.'strawberry']
for i, flavor in enumerate(flavor_list):
    print(f'{i + 1}: {flavor}')

for i, flavor in enumerate(flavor_list, 1) :print(f'{i}: {flavor}')
Copy the code

Rule 8 uses the zip function to iterate over both iterators simultaneously

import itertools

names = ['Cecilia'.'Lise'.'Marie']
counts = [len(n) for n in names]
for name, count in itertools.zip_longest(names, counts):
    print(f'{name}: {count}')
Copy the code

# 9 Do not write else blocks after for and while loops

def coprime_alternate(a, b) :
    is_coprime = True
    for i in range(2.min(a, b) + 1) :if a % i == 0 and b % i == 0:
            is_coprime = False
            break
    return is_coprime

assert coprime_alternate(4.9)
assert not coprime_alternate(3.6)
Copy the code

10. Use assignment expressions to reduce duplicate code

FRUIT_TO_PICK = [
    {'apple': 1.'banana': 3},
    {'lemon': 2.'lime': 5},
    {'orange': 3.'melon': 2},
]

bottles = []
while fresh_fruit := pick_fruit():
    for fruit, count in fresh_fruit.items():
        batch = make_juice(fruit, count)
        bottles.extend(batch)

print(bottles)
Copy the code