Effective Python Learning Memorandum Day 3 [3/100]

Introduction

The other day I learned about 100 Days Of Code, which was popular on Twitter for a while. The purpose of this article is to keep a record and output how much I, as a beginner, can grow through 100 days of study. I think there are many mistakes and difficult to read. I would appreciate it if you could point out!

Teaching materials to be learned this time

Today's progress

--Progress: Pages 29-37 ――I will write down what I often forget or didn't know about what I learned today.

Choose an exception rather than returning None

In python, None, 0, empty string, etc. are all evaluated as False in the conditional expression. Therefore, using None for the return value can cause unexpected problems. Use the bool method to check.

a = 0
b = []
c = {}
d = None
e = ''
bool(a)
# False
bool(b)
# False
bool(c)
# False
bool(d)
# False
bool(e)
# False

As an example of the problem that arises when using None, consider a helper function that divides one number by another. If you divide by zero, the result is undefined, so define it to return None.

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

Consider the case where the result of a / b is zero. At this time, both None and 0 are judged to be False in the conditional expression, so the following conditions will result in an erroneous result.

a, b = 0, 5
result = divide(a, b):
    if not result:
        print('Invalid inputs')  #mistake

The solution to this problem is to not return None in the first place, but raise an exception to the caller to handle it.

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        raise ValueError('Invalid inputs') from e

If the function does not raise an exception, it can be determined that the return value should be okay.

Know how closures relate to variable scope

--A closure is a function that references a variable in the defined scope. --Closer functions can reference variables from anywhere in the defined scope --By default closures are variable assignments and cannot affect surrounding scopes --In python3, the closure can modify variables in the outer scope using nonlocal minutes. --Use nonlocal minutes only in simple functions

Check the scope range

def scope1(x):
    number = x
    def scope2(x):
        number = 1
    scope2(number)
    return number

number = 0
x = scope1(number)
print(x)
# 0

I assigned 1 to number in scope2, but the return value is 0. This is because the scope is different. Since the number in scope1 and the number in scope2 are processed as different variables, the values ​​have not changed. To traverse variables in different scopes, use nonlocal and define:

def scope1(x):
    number = x
    print(x)
    def scope2(x):
        nonlocal number 
        number = 1
    scope2(number)
    return number

number = 0
x = scope1(number)
print(x)
# 1

Consider returning a generator without returning a list

--Using a generator makes the code clearer than returning a list of stored results --The iterator returned by the generator produces a set of values ​​passed to the yield expression in the body of the generator function. --The generator does not have to hold all inputs and outputs in working memory, so it can generate a sequence of outputs for inputs of any length.

Code returned in list

def index_words(text):
    result = []
    if text:
        result.append(0)
    for index, letter in enumerate(text):
        if letter == ' ':
            result.append(index + 1)
    return result

words = 'Hello Effective Python'
result = index_words(words)
print(result)

Output result

[0, 6, 16]

Code returned by the generator

def index_words(text):
    result = []
    if text:
        yield 0
    for index, letter in enumerate(text):
        if letter == ' ':
            yield index + 1
    return result

#The generator returned by the generator call can be converted to list with the built-in function list
result = list(index_words(words))
print(result)

Output result

[0, 6, 16]

Recommended Posts

Effective Python Learning Memorandum Day 6 [6/100]
Effective Python Learning Memorandum Day 12 [12/100]
Effective Python Learning Memorandum Day 9 [9/100]
Effective Python Learning Memorandum Day 8 [8/100]
Effective Python Learning Memorandum Day 14 [14/100]
Effective Python Learning Memorandum Day 1 [1/100]
Effective Python Learning Memorandum Day 13 [13/100]
Effective Python Learning Memorandum Day 3 [3/100]
Effective Python Learning Memorandum Day 5 [5/100]
Effective Python Learning Memorandum Day 4 [4/100]
Effective Python Learning Memorandum Day 7 [7/100]
Effective Python Learning Memorandum Day 2 [2/100]
Python learning day 4
Python memorandum
Python Memorandum 2
Python memorandum
python learning
python memorandum
python memorandum
Python day 1
Python memorandum
python memorandum
Python memorandum
Python basics memorandum
[Python] Learning Note 1
Python learning notes
Python pathlib memorandum
Python memorandum (algorithm)
Deep Learning Memorandum
Python learning site
Python Deep Learning
Python learning (supplement)
Deep learning × Python
Python memorandum [links]
python learning notes
Python study day 1
Machine learning starting with Python Personal memorandum Part2
Machine learning starting with Python Personal memorandum Part1
Python memorandum numbering variables
Python class (Python learning memo ⑦)
"Object-oriented" learning with python
Python module (Python learning memo ④)
Reinforcement learning 1 Python installation
Python: Deep Learning Practices
Python ~ Grammar speed learning ~
python memorandum (sequential update)
Python: Unsupervised Learning: Basics
Learning record 4 (8th day)
Learning record 9 (13th day)
Learning record 3 (7th day)
Learning record 5 (9th day)
Learning record 6 (10th day)
Python memorandum (personal bookmark)
Learning record 8 (12th day)
Learning record 1 (4th day)
Learning record 7 (11th day)
Private Python learning procedure
Learning Python with ChemTHEATER 02
Python basic memorandum part 2
Learning Python with ChemTHEATER 01
Python: Deep Learning Tuning