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

วันที่ 11 — ฟังก์ชัน (Functions)

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

เรียนรู้การสร้างและใช้งาน Function ใน Python ตั้งแต่พื้นฐาน parameters, return values, default args, *args และ higher-order functions

ฟังก์ชัน (Functions)

จนถึงตอนนี้เราได้ใช้ built-in functions ของ Python มาหลายตัวแล้ว ในส่วนนี้จะเน้นที่ custom functions Function คือ block ของโค้ดที่นำมาใช้ซ้ำได้ หรือ programming statements ที่ออกแบบมาเพื่อทำงานอย่างใดอย่างหนึ่ง ใน Python เราใช้ keyword def เพื่อประกาศ function ส่วน block ของ code จะรันเมื่อมีการเรียกใช้งาน function

การประกาศและเรียกใช้ Function

เมื่อเราสร้าง function เราใช้ keyword def ต่อไปนี้คือ syntax:

python
# syntax
# Declaring a function
def function_name():
    codes
    codes
# Calling a function
function_name()

Function ที่ไม่มี Parameters

Function สามารถประกาศโดยไม่มี parameters ได้

python
def generate_full_name ():
    first_name = 'Asabeneh'
    last_name = 'Yetayeh'
    space = ' '
    full_name = first_name + space + last_name
    print(full_name)
generate_full_name () # calling a function

def add_two_numbers ():
    num_one = 2
    num_two = 3
    total = num_one + num_two
    print(total)
add_two_numbers()

Function ที่มีการ Return ค่า — ส่วนที่ 1

Function สามารถ return ค่าได้โดยใช้ return statement ถ้าไม่มี return statement function จะ return ค่า None โดย default เขียน function ข้างต้นใหม่โดยใช้ return:

python
def generate_full_name ():
    first_name = 'Asabeneh'
    last_name = 'Yetayeh'
    space = ' '
    full_name = first_name + space + last_name
    return full_name
print(generate_full_name())

def add_two_numbers ():
    num_one = 2
    num_two = 3
    total = num_one + num_two
    return total
print(add_two_numbers())

Function ที่มี Parameters

ใน function เราสามารถรับข้อมูลชนิดต่าง ๆ ผ่าน parameters ได้ — single parameter:

python
  # syntax
  # Declaring a function
  def function_name(parameter):
    codes
    codes
  # Calling function
  print(function_name(argument))
python
def greetings (name):
    message = name + ', welcome to Python for Everyone!'
    return message
print(greetings('Asabeneh'))

def add_ten(num):
    ten = 10
    return num + ten
print(add_ten(90))

def square_number(x):
    return x * x
print(square_number(2))

def area_of_circle (r):
    PI = 3.14
    area = PI * r ** 2
    return area
print(area_of_circle(10))

def sum_of_numbers(n):
    total = 0
    for i in range(n+1):
        total+=i
    return total
print(sum_of_numbers(10)) # 55
print(sum_of_numbers(100)) # 5050

Multiple parameters:

python
  # syntax
  # Declaring a function
  def function_name(para1, para2):
    codes
    codes
  # Calling function
  print(function_name(arg1, arg2))
python
def generate_full_name (first_name, last_name):
    space = ' '
    full_name = first_name + space + last_name
    return full_name
print('Full Name: ', generate_full_name('Asabeneh','Yetayeh'))

def sum_two_numbers (num_one, num_two):
    sum = num_one + num_two
    return sum
print('Sum of two numbers: ', sum_two_numbers(1, 9))

def calculate_age (current_year, birth_year):
    age = current_year - birth_year
    return age 
print('Age: ', calculate_age(2021, 1819))

def weight_of_object (mass, gravity):
    weight = str(mass * gravity)+ ' N' # the value has to be changed to a string first
    return weight
print('Weight of an object in Newtons: ', weight_of_object(100, 9.81))

การส่ง Arguments ด้วย Key และ Value

ถ้าเราส่ง arguments ด้วย key และ value ลำดับของ arguments จะไม่สำคัญ:

python
# syntax
# Declaring a function
def function_name(para1, para2):
    codes
    codes
# Calling function
print(function_name(para1 = 'John', para2 = 'Doe')) # the order of arguments does not matter here
python
def print_fullname(firstname, lastname):
    space = ' '
    full_name = firstname  + space + lastname
    print(full_name)
print_fullname(firstname = 'Asabeneh', lastname = 'Yetayeh')

def add_two_numbers (num1, num2):
    total = num1 + num2
    return total
print(add_two_numbers(num2 = 3, num1 = 2)) # Order does not matter

Function ที่มีการ Return ค่า — ส่วนที่ 2

ถ้าเราไม่ return ค่าจาก function function จะ return None โดย default เราสามารถ return data type ไหนก็ได้:

Return string:

python
def print_name(firstname):
    return firstname
print_name('Asabeneh') # Asabeneh

def print_full_name(firstname, lastname):
    space = ' '
    full_name = firstname  + space + lastname
    return full_name
print_full_name(firstname='Asabeneh', lastname='Yetayeh')

Return number:

python
def add_two_numbers (num1, num2):
    total = num1 + num2
    return total
print(add_two_numbers(2, 3))

def calculate_age (current_year, birth_year):
    age = current_year - birth_year
    return age
print('Age: ', calculate_age(2019, 1819))

Return boolean:

python
def is_even (n):
    if n % 2 == 0:
        return True    # return stops further execution of the function, similar to break 
    return False
print(is_even(10)) # True
print(is_even(7)) # False

Return list:

python
def find_even_numbers(n):
    evens = []
    for i in range(n + 1):
        if i % 2 == 0:
            evens.append(i)
    return evens
print(find_even_numbers(10))

Function ที่มี Default Parameters

บางครั้งเราส่ง default values ให้ parameters ถ้าเราไม่ส่ง arguments ตอนเรียกใช้ function ค่า default จะถูกใช้:

python
# syntax
# Declaring a function
def function_name(param = value):
    codes
    codes
# Calling function
function_name()
function_name(arg)
python
def greetings (name = 'Peter'):
    message = name + ', welcome to Python for Everyone!'
    return message
print(greetings())
print(greetings('Asabeneh'))

def generate_full_name (first_name = 'Asabeneh', last_name = 'Yetayeh'):
    space = ' '
    full_name = first_name + space + last_name
    return full_name

print(generate_full_name())
print(generate_full_name('David','Smith'))

def calculate_age (birth_year,current_year = 2021):
    age = current_year - birth_year
    return age 
print('Age: ', calculate_age(1821))

def weight_of_object (mass, gravity = 9.81):
    weight = str(mass * gravity)+ ' N' # the value has to be changed to string first
    return weight
print('Weight of an object in Newtons: ', weight_of_object(100)) # 9.81 - average gravity on Earth's surface
print('Weight of an object in Newtons: ', weight_of_object(100, 1.62)) # gravity on the surface of the Moon

Arbitrary Number of Arguments

ถ้าเราไม่รู้จำนวน arguments ที่จะส่งเข้ามา เราสามารถสร้าง function ที่รับ arguments จำนวนไม่แน่นอนได้ โดยเพิ่ม * ไว้หน้าชื่อ parameter:

python
# syntax
# Declaring a function
def function_name(*args):
    codes
    codes
# Calling function
function_name(param1, param2, param3,..)
python
def sum_all_nums(*nums):
    total = 0
    for num in nums:
        total += num     # same as total = total + num 
    return total
print(sum_all_nums(2, 3, 5)) # 10

Default และ Arbitrary Number of Parameters

python
def generate_groups (team,*args):
    print(team)
    for i in args:
        print(i) 
generate_groups('Team-1','Asabeneh','Brook','David','Eyob')

Dictionary Unpacking

เราสามารถเรียก function ที่มี named arguments โดยใช้ dictionary ที่มี key ตรงกันได้ โดยใช้ **:

python
# Define a function that takes two arguments: 'name' and 'location'
def greet(name, location):
    # Print a greeting message using the provided arguments
    print("Hi there", name, "how is the weather in", location)

# Call the function using keyword arguments
greet(name="Alice", location="New York")
# Output: Hi there Alice how is the weather in New York

# Create a dictionary with keys matching the function's parameter names
my_dict = {"name": "Alice", "location": "New York"}

# Call the function using dictionary unpacking
greet(**my_dict)
# The ** operator unpacks the dictionary, passing its key-value pairs
# as keyword arguments to the function.
# Output: Hi there Alice how is the weather in New York

Arbitrary Number of Named Arguments

เราสามารถกำหนด function ให้รับ named arguments จำนวนไม่แน่นอนได้:

python
def arbitrary_named_args(**args):
    print("I received an arbitrary number of arguments, totaling", len(args))
    print("They are provided as a dictionary in my function:", type(args))
    print("Let's print them:")
    for k, v in args.items():
        print(" * key:", k, "value:", v)

โดยทั่วไปหลีกเลี่ยงการใช้แบบนี้ถ้าไม่จำเป็น เพราะทำให้ยากต่อการเข้าใจว่า function รับอะไรบ้าง

Function เป็น Parameter ของอีก Function หนึ่ง

python
#You can pass functions around as parameters
def square_number (n):
    return n ** n
def do_something(f, x):
    return f(x)
print(do_something(square_number, 3)) # 27

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

ระดับ 1

  1. ประกาศ function ชื่อ add_two_numbers รับ 2 parameters แล้ว return ผลรวม
  2. พื้นที่วงกลมคำนวณได้จาก area = π x r x r เขียน function ที่คำนวณ area_of_circle
  3. เขียน function ชื่อ add_all_nums รับ arguments จำนวนไม่แน่นอนแล้วรวมทุก arguments เช็คว่า list items ทั้งหมดเป็น number type หรือไม่ ถ้าไม่ใช่ให้แสดง feedback ที่เหมาะสม
  4. อุณหภูมิหน่วย °C แปลงเป็น °F ได้ด้วยสูตร: °F = (°C x 9/5) + 32 เขียน function แปลง °C เป็น °F ชื่อ convert_celsius_to_fahrenheit
  5. เขียน function ชื่อ check_season รับ month parameter แล้ว return ฤดูกาล: Autumn, Winter, Spring หรือ Summer
  6. เขียน function ชื่อ calculate_slope ที่ return ค่า slope ของสมการเส้นตรง
  7. สมการ Quadratic คือ ax² + bx + c = 0 เขียน function ที่คำนวณ solution set ของสมการ ชื่อ solve_quadratic_eqn
  8. ประกาศ function ชื่อ print_list รับ list เป็น parameter แล้ว print แต่ละ element ของ list
  9. ประกาศ function ชื่อ reverse_list รับ array เป็น parameter แล้ว return array ที่กลับลำดับแล้ว (ใช้ loop)
python
print(reverse_list([1, 2, 3, 4, 5]))
# [5, 4, 3, 2, 1]
print(reverse_list(["A", "B", "C"]))
# ["C", "B", "A"]
  1. ประกาศ function ชื่อ capitalize_list_items รับ list เป็น parameter แล้ว return list ที่ capitalize items แล้ว
  2. ประกาศ function ชื่อ add_item รับ list และ item เป็น parameters แล้ว return list ที่เพิ่ม item ต่อท้ายแล้ว
python
food_stuff = ['Potato', 'Tomato', 'Mango', 'Milk'];
print(add_item(food_stuff, 'Meat'))     # ['Potato', 'Tomato', 'Mango', 'Milk','Meat'];
numbers = [2, 3, 7, 9];
print(add_item(numbers, 5))      # [2, 3, 7, 9, 5]
  1. ประกาศ function ชื่อ remove_item รับ list และ item เป็น parameters แล้ว return list ที่ลบ item ออกแล้ว
python
food_stuff = ['Potato', 'Tomato', 'Mango', 'Milk']
print(remove_item(food_stuff, 'Mango'))  # ['Potato', 'Tomato', 'Milk'];
numbers = [2, 3, 7, 9]
print(remove_item(numbers, 3))  # [2, 7, 9]
  1. ประกาศ function ชื่อ sum_of_numbers รับตัวเลข n เป็น parameter แล้วรวมตัวเลขทั้งหมดใน range นั้น
python
print(sum_of_numbers(5))  # 15
print(sum_of_numbers(10)) # 55
print(sum_of_numbers(100)) # 5050
  1. ประกาศ function ชื่อ sum_of_odds รับตัวเลข n เป็น parameter แล้วรวมเลขคี่ทั้งหมดใน range นั้น
  2. ประกาศ function ชื่อ sum_of_even รับตัวเลข n เป็น parameter แล้วรวมเลขคู่ทั้งหมดใน range นั้น

ระดับ 2

  1. ประกาศ function ชื่อ evens_and_odds รับ positive integer เป็น parameter แล้วนับจำนวนเลขคู่และเลขคี่ในตัวเลขนั้น
python
print(evens_and_odds(100))
# The number of odds are 50.
# The number of evens are 51.
  1. เรียก function ของคุณว่า factorial รับ whole number เป็น parameter แล้ว return factorial ของตัวเลขนั้น
  2. เรียก function ของคุณว่า is_empty รับ parameter แล้วเช็คว่าว่างเปล่าหรือไม่
  3. เขียน functions ต่าง ๆ ที่รับ list เป็น parameter: calculate_mean, calculate_median, calculate_mode, calculate_range, calculate_variance, calculate_std (standard deviation)
  4. เขียน function ชื่อ greet ที่มี default argument ชื่อ name ถ้าไม่มี argument ให้ print 'Hello, Guest!' ถ้ามีให้ greet ด้วยชื่อนั้น
python
greet()
# "Hello, Guest!"
greet("Alice")
# "Hello, Alice!"
  1. สร้าง function ชื่อ show_args ที่รับ named arguments จำนวนไม่แน่นอนแล้ว print ชื่อและค่าของแต่ละ argument
python
show_args(name="Alice", age=30, city="New York")
# Received: name: Alice, age: 30, city: New York
show_args(name="Bob", pet="Fluffy, the bunny")
# Received: name: Bob, pet: Fluffy, the bunny

ระดับ 3

  1. เขียน function ชื่อ is_prime ที่เช็คว่าตัวเลขนั้นเป็น prime หรือไม่
  2. เขียน function ที่เช็คว่า items ทั้งหมดใน list มีค่า unique หรือไม่
  3. เขียน function ที่เช็คว่า items ทั้งหมดใน list เป็น data type เดียวกันหรือไม่
  4. เขียน function ที่เช็คว่า variable ที่ส่งมาเป็น valid Python variable name หรือไม่
  5. ไปที่โฟลเดอร์ data แล้วเปิดไฟล์ countries-data.py สร้าง function ชื่อ most_spoken_languages ที่ return 10 หรือ 20 ภาษาที่มีคนพูดมากที่สุดในโลกตามลำดับจากมากไปน้อย สร้าง function ชื่อ most_populated_countries ที่ return 10 หรือ 20 ประเทศที่มีประชากรมากที่สุดตามลำดับ