Python เบื้องต้น: การเขียนฟังก์ชัน
Hugo Bowne-Anderson
Instructor
กำหนดฟังก์ชันแบบไม่มีพารามิเตอร์
กำหนดฟังก์ชันที่มีพารามิเตอร์หนึ่งตัว
กำหนดฟังก์ชันที่คืนค่า
ถัดไป: อาร์กิวเมนต์หลายตัว, ค่าที่คืนหลายค่า
str()x = str(5)
print(x)
'5'
print(type(x))
<class 'str'>
def square(): # <- Function headernew_value = 4 ** 2 # <- Function body print(new_value)square()
16
def square(value):
new_value = value ** 2
print(new_value)
square(4)
16
square(5)
25
def square(value): new_value = value ** 2 return new_valuenum = square(4) print(num)
16
Docstring อธิบายว่าฟังก์ชันทำอะไร
ทำหน้าที่เป็นเอกสารประกอบฟังก์ชัน
วางไว้ในบรรทัดถัดจาก function header ทันที
อยู่ระหว่างเครื่องหมาย triple double quotes """
def square(value):
"""Returns the square of a value."""
new_value = value ** 2
return new_value
Python เบื้องต้น: การเขียนฟังก์ชัน