Notes & software courses · Free to learn
Aph's Blog
On this page

วันที่ 17 — จัดการข้อผิดพลาด (Exception Handling)

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

เรียนรู้การจัดการ Exception ด้วย try/except/else/finally พร้อม Packing/Unpacking Arguments, Spreading, Enumerate และ Zip

Exception Handling

Python ใช้ try และ except เพื่อจัดการ errors อย่างสวยงาม ทำให้โปรแกรมไม่หยุดทำงานเมื่อเจอ error ที่ไม่คาดคิด การออกแบบนี้เรียกว่า try and except

Try and Except
โครงสร้าง try/except ใน Python
python
try:
    code in this block if things go well
except:
    code in this block run if things go wrong

ตัวอย่าง:

python
try:
    print(10 + '5')
except:
    print('Something went wrong')

ตัวอย่างที่สองแสดงการรับ input และจับ exception เฉพาะประเภท:

python
try:
    name = input('Enter your name:')
    year_born = input('Year you were born:')
    age = 2019 - year_born
    print(f'You are {name}. And your age is {age}.')
except TypeError:
    print('Type error occur')
except ValueError:
    print('Value error occur')
except ZeroDivisionError:
    print('zero division error occur')

เพิ่ม else และ finally เพื่อจัดการ flow ให้ครบ:

python
try:
    name = input('Enter your name:')
    year_born = input('Year you born:')
    age = 2019 - int(year_born)
    print(f'You are {name}. And your age is {age}.')
except TypeError:
    print('Type error occur')
except ValueError:
    print('Value error occur')
except ZeroDivisionError:
    print('zero division error occur')
else:
    print('I usually run with the try block')
finally:
    print('I alway run.')

การใช้ except Exception as e เพื่อดูรายละเอียดข้อผิดพลาด:

python
try:
    name = input('Enter your name:')
    year_born = input('Year you born:')
    age = 2019 - int(year_born)
    print(f'You are {name}. And your age is {age}.')
except Exception as e:
    print(e)

Packing and Unpacking Arguments in Python

เราใช้ operators สองตัวสำหรับ packing และ unpacking:
* สำหรับ tuples
** สำหรับ dictionaries

Unpacking

Unpacking Lists

python
def sum_of_five_nums(a, b, c, d, e):
    return a + b + c + d + e

lst = [1, 2, 3, 4, 5]
print(sum_of_five_nums(*lst))  # 15
python
first, second, third, *rest, tenth = [1,2,3,4,5,6,7,8,9,10]
print(first)          # 1
print(second)         # 2
print(third)          # 3
print(rest)           # [4,5,6,7,8,9]
print(tenth)          # 10
python
from math import sqrt

numbers = (36, 49, 81, 100, 144)
print(list(map(sqrt, numbers)))
python
numbers = range(2, 7)  # normal call with separate arguments
print(list(numbers)) # [2, 3, 4, 5, 6]
args = [2, 7]
print(list(range(*args)))   # call with arguments unpacked from a list

Unpacking Dictionaries

python
def unpacking_person_info(name, country, city, age):
    return f'{name} lives in {country}, {city}. He is {age} year old.'
dct = {'name':'Asabeneh', 'country':'Finland', 'city':'Helsinki', 'age':250}
print(unpacking_person_info(**dct))

Packing

Packing Lists

python
def sum_all(*args):
    s = 0
    for i in args:
        s += i
    return s
print(sum_all(1, 2, 3))             # 6
print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28

Packing Dictionaries

python
def packing_person_info(**kwargs):
    # check the type of kwargs and it is a dict type
    # print(type(kwargs))
    # Printing dictionary items
    for key in kwargs:
        print("{key} = {value}".format(key=key, value=kwargs[key]))
    return kwargs

print(packing_person_info(name="Asabeneh",
      country="Finland", city="Helsinki", age=250))

Spreading in Python

python
lst_one = [1, 2, 3]
lst_two = [4, 5, 6, 7, 8, 9, 10]
lst = [0, *lst_one, *lst_two]
print(lst)          # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries)  # ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']

Enumerate

ถ้าเราต้องการ index ของแต่ละ item ใน list เราใช้ enumerate เพื่อรับ index และ item พร้อมกัน:

python
for index, item in enumerate([20, 30, 40]):
    print(index, item)
python
for index, i in enumerate(countries):
    print('hi')
    if i == 'Finland':
        print(f'The country {i} has been found at index {index}')

Zip

บางครั้งเราต้องการ loop หลาย list พร้อมกัน เราสามารถใช้ zip เพื่อ combine lists:

python
fruits = ['banana', 'orange', 'mango', 'lemon', 'lime']
vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
fruits_and_vegs = [(f, v) for f, v in zip(fruits, vegetables)]
print(fruits_and_vegs)  # [('banana', 'Tomato'), ('orange', 'Potato'), ('mango', 'Cabbage'), ('lemon', 'Onion'), ('lime', 'Carrot')]

💻 แบบฝึกหัด — วันที่ 17

  1. แตก (Unpack) 5 ประเทศแรกออกมาเก็บในตัวแปร nordic_countries และเก็บ Estonia กับ Russia ใน es และ ru ตามลำดับ
python
names = ['Finland', 'Sweden', 'Norway','Denmark','Iceland', 'Estonia','Russia']