Direction: ไปที่ File -> Save a copy in Drive (ต้องมี gmail account)แล้วทำปฏิบัติการในไฟล์ใหม่ที่สร้างขึ้นมา

Iteration¶

ตัวอย่างของ iteration ที่เห็นได้บ่อยที่สุดคือการใช้ for loop

In [1]:
#Range

for i in range(2, 10, 2):
  print(i)
2
4
6
8
In [2]:
#List

for num in [2, 4, 6, 8]:
  print(num)
2
4
6
8

enumerate¶

สมมติว่าข้างล่างนี้คือตัวอย่างของการทำนาย time series ใน 10 วันข้างหน้า

In [3]:
forecast = [34, 62, 21, 87, 95, 21, 42, 17, 39, 23]

สามารถใช้ for loop คู่กับ enumerate ในการดูว่าแต่ละค่านั้นคือค่าทำนายของวันที่เท่าไหร่

In [4]:
for i, num in enumerate(forecast):
  print(f"Forecast of Day {i} is {num}")
Forecast of Day 0 is 34
Forecast of Day 1 is 62
Forecast of Day 2 is 21
Forecast of Day 3 is 87
Forecast of Day 4 is 95
Forecast of Day 5 is 21
Forecast of Day 6 is 42
Forecast of Day 7 is 17
Forecast of Day 8 is 39
Forecast of Day 9 is 23

Iterator¶

อีกวิธีหนึ่งในการสร้าง loop นอกจากการใช้ range หรือ list แล้ว เราสามารถสร้าง iterator โดยใช้ฟังก์ชัน iter ครอบ list ของสิ่งที่เราอยากจะให้วน loop ไปเรื่อย ๆ

In [5]:
#iter

current_number = iter([2, 4, 6, 8])
In [6]:
#next

next(current_number)
Out[6]:
2
In [7]:
#for loop
for num in current_number:
  print(num)
4
6
8

ซึ่งข้อดีของการใช้ iter คือเราสามารถเลือกให้วน loop กลับมาที่จุดเริ่มต้นได้

In [8]:
#for loop
current_number = iter([2, 4, 6, 8])

for i in range(4):
  print(next(current_number))
2
4
6
8

zip¶

บางครั้งเราต้องการวน loop ตาม items ในหลายๆ list พร้อมกัน ตัวอย่างเช่นชื่อ สัญชาติ และสาขาของนักวิจัย 12 ท่านข้างล่างนี้

In [9]:
names = (
    'Frances Arnold', 'George Smith', 'Gregory Winter',
    'Denis Mukwege', 'Nadia Murad',
    'Arthur Ashkin', 'Gérard Mourou', 'Donna Strickland',
    'James Allison', 'Tasuku Honjo',
    'William Nordhaus', 'Paul Romer'
)

nationalities = (
    'USA', 'USA', 'UK',
    'DRC', 'Iraq',
    'USA', 'France', 'Canada',
    'USA', 'Japan',
    'USA', 'USA'
)

categories = (
    'Chemistry', 'Chemistry', 'Chemistry',
    'Peace', 'Peace',
    'Physics', 'Physics', 'Physics',
    'Physiology or Medicine', 'Physiology or Medicine',
    'Economics', 'Economics'
)
In [10]:
#zip

scientists = zip(names, nationalities, categories)
In [11]:
#next

next(scientists)
Out[11]:
('Frances Arnold', 'USA', 'Chemistry')
In [12]:
#for loop
for name, nation, cat in zip(names, nationalities, categories):
  print(f"{name} was born {nation} is a researcher in {cat}.")
Frances Arnold was born USA is a researcher in Chemistry.
George Smith was born USA is a researcher in Chemistry.
Gregory Winter was born UK is a researcher in Chemistry.
Denis Mukwege was born DRC is a researcher in Peace.
Nadia Murad was born Iraq is a researcher in Peace.
Arthur Ashkin was born USA is a researcher in Physics.
Gérard Mourou was born France is a researcher in Physics.
Donna Strickland was born Canada is a researcher in Physics.
James Allison was born USA is a researcher in Physiology or Medicine.
Tasuku Honjo was born Japan is a researcher in Physiology or Medicine.
William Nordhaus was born USA is a researcher in Economics.
Paul Romer was born USA is a researcher in Economics.

นอกจาก list และ tuple แล้วเราสามารถ zip iterators ไว้ด้วยกันได้ด้วย

In [13]:
items = iter(["pen", "paper", "pencil", "eraser"])
prices = iter([12, 1, 7, 9])

for item, price in zip(items, prices):
  print(f"The price of {item} is {price} baht")
The price of pen is 12 baht
The price of paper is 1 baht
The price of pencil is 7 baht
The price of eraser is 9 baht

Errors and Exception handling¶

SyntaxError¶

เกิดขึ้นในกรณีที่โค้ดมี format ที่ไม่ถูกต้องตามหลักการของ python หรือว่ามีโค้ดบางส่วนที่ขาดหายไป

In [14]:
my_list = [1,2,3
  Cell In [14], line 1
    my_list = [1,2,3
                    ^
SyntaxError: incomplete input
In [15]:
for i in range(5)
  print(i)
  Cell In [15], line 1
    for i in range(5)
                     ^
SyntaxError: expected ':'
In [16]:
import numpy as np

my_list = [2, 65, 82, 13, 845, 84, 265, 97, 43]

variance = np.sum(np.array(my_list) - np.mean(my_list)**2)/(len(my_list) - 1)

print(variance)
-30896.55555555556

RuntimeError¶

เกิดขึ้นในกรณีที่โค้ดผ่านการเช็ค format ผ่าน แต่เกิดปัญหาขึ้นตอนรันโค้ด

1. TypeError¶

In [17]:
print(4, "Kings")
4 Kings

2. IndexError¶

In [18]:
mylist = [1, 2, 3, 4]
print(mylist[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In [18], line 2
      1 mylist = [1, 2, 3, 4]
----> 2 print(mylist[4])

IndexError: list index out of range
In [19]:
import numpy as np

myarray = np.array([[1, 2], 
                    [3, 4]])
myarray[2,2]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In [19], line 5
      1 import numpy as np
      3 myarray = np.array([[1, 2], 
      4                     [3, 4]])
----> 5 myarray[2,2]

IndexError: index 2 is out of bounds for axis 0 with size 2

3. KeyError¶

In [20]:
mydict = {'Will': 14, 'Lucas': 14, 'Dustin': 14}

mydict["Mike"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In [20], line 3
      1 mydict = {'Will': 14, 'Lucas': 14, 'Dustin': 14}
----> 3 mydict["Mike"]

KeyError: 'Mike'

4. NameError¶

In [21]:
import pandas as pd

X = pd.read_csv(sample_data/mnist_test.csv)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [21], line 3
      1 import pandas as pd
----> 3 X = pd.read_csv(sample_data/mnist_test.csv)

NameError: name 'sample_data' is not defined
In [22]:
mylist = [2, 65, 82, 13, 845, 84, 265, 97, 43]

#Count number of elements in mylist

count = 0
for num in mylist:
  count += 1

print(count)
9

5. IndentationError¶

In [23]:
for num in [1,2,3,4]:
print num
  Cell In [23], line 2
    print num
    ^
IndentationError: expected an indented block after 'for' statement on line 1
In [24]:
for num in [1,2,3,4]:
  for word in ['one', 'two', 'three']:
  print(num)
  Cell In [24], line 3
    print(num)
    ^
IndentationError: expected an indented block after 'for' statement on line 2

6. OverflowError¶

In [25]:
x = 10 #int

print(x**309)
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

วิธีการหาและแก้ bug ใน python

  1. หา line ที่มี error

    ใส่ print ลงไปในที่ต่างๆ ของโค้ดเพื่อหาจุดผิด

  2. ถ้าไม่เคยเห็น error ชนิดนั้นมาก่อน หรือไม่รู้วิธีแก้ไข ลองนำ error กับชื่อ package ที่ใช้ไปค้นหาใน google ว่าเคยมีคนที่เคยเจอปัญหาเหมือนกันหรือไม่

In [26]:
import numpy as np

num = (1,2,3,4,5,6,7)

np.mean(num)
Out[26]:
4.0

Exercise: แก้ error ในโค้ดข้อ 1-6 ข้างล่างนี้¶

1.

In [27]:
authrs = {
    "Charles Dickens": "1870",
    "William Thackeray": "1863",
    "Anthony Trollope": "1882",
    "Gerard Manley Hopkins": "1889"

for author date in authors.items{}:
    print(f"{author} died in {date}")
}
  Cell In [27], line 7
    for author date in authors.items{}:
    ^
SyntaxError: invalid syntax

2.

In [28]:
year == int.input("What year were you born? '))

if year <= 1996
    print("You are a Millennial!")
elif year > 1996 && year < 2012:
    print("You are a Zoomer!")
elif:
    print("You are an Alpha!")
  Cell In [28], line 1
    year == int.input("What year were you born? '))
                      ^
SyntaxError: unterminated string literal (detected at line 1)

3.

In [29]:
class Person:
  def init(self, first_name, last_name):
    self.first = first_name
    self.last = last_nme
  def speak(self):
  print("My name is + " self.first + " " + self.last)

me = Person("Timothee", "Chalamet")
you = Person("Jennifer", "Lawrence")

me.speak
you.speak
  Cell In [29], line 6
    print("My name is + " self.first + " " + self.last)
    ^
IndentationError: expected an indented block after function definition on line 5
  1. ฟังก์ชัน minimum มี input เป็น list ใช้ในการหาสมาชิกที่ต่ำที่สุดใน list นั้น แต่พอลองทดสอบฟังก์ชันข้างล่างพบว่า output ไม่เป็นไปตามที่คาดหวังไว้ จงแก้ไขฟังก์ชันให้ถูกต้อง
In [30]:
def minimum(some_list):
    a = 0
    for x in range(1, len(some_list)):
        if some_list[x] < a:
            a = some_list[x]
    return a

minimum([76,31,90,39,12])
Out[30]:
0
  1. แก้โค้ดข้างล่างต่อไปนี้ เพื่อแสดงผลอุณหภูมิในแต่ละเดือนตั้งแต่เดือนมกราคม (Jan) ถึงเดือนธันวาคม (Dec)
In [31]:
months = iter(['Jun', 'Feb','Mar', 'Apr', 
          "May", "Jun", "Jul", "Aug",
          "Sep", "Oct", "Nov", "Dec"])
temps = iter([27, 28, 30, 31, 30, 30, 30, 30, 29, 29, 28, 26])

months_temps = (months, temps)

for i in range(12):
  month, temp = next(months_temps)
  print(f"Average temperature in {month} is {temp}C")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [31], line 9
      6 months_temps = (months, temps)
      8 for i in range(12):
----> 9   month, temp = next(months_temps)
     10   print(f"Average temperature in {month} is {temp}C")

TypeError: 'tuple' object is not an iterator
In [ ]:

  1. สมมติว่าเรามี array สองตัวคือ

x = [1, 2, 3] และ y = [[4, 5, 6], [7, 8, 9]]

ต้องการนำ x และ y มาต่อกันให้ได้ array ที่มีขนาด 3x3 ดังนี้:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

ด้วยการใช้ฟังก์ชัน np.concatenate (reference) แต่ว่าลองรันโค้ดข้างล่างแล้วเกิด error ขึ้นมา

ลองทำการศึกษา reference ที่ให้ไว้ข้างบนและลองใช้ google เพื่อหาวิธีในการแก้ error ในโค้ดข้างล่างนี้

In [32]:
import numpy as np

x = np.array([1, 2, 3])
y = np.array([[4, 5, 6],[7, 8, 9]])

np.concatenate((x,y), axis = 0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In [32], line 6
      3 x = np.array([1, 2, 3])
      4 y = np.array([[4, 5, 6],[7, 8, 9]])
----> 6 np.concatenate((x,y), axis = 0)

File <__array_function__ internals>:180, in concatenate(*args, **kwargs)

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)

อย่าลืม log out gmail หลังทำปฏิบัติการเสร็จสิ้น