Python Functions: def, Parameters and return
Write code once and reuse it everywhere. Define functions with parameters, default values and return values.
- Defining a function with def
- Parameters, arguments and default values
- Returning results
- 1
"Grace"The argument goes in - 2
def greet(name):The body runs with name = "Grace" - 3
return f"Hello, {name}!"The result comes back
Input, work, output
ฟังก์ชัน (function) คือบล็อกโค้ดที่มีชื่อและนำกลับมาใช้ได้หลายครั้ง คุณส่งข้อมูลให้ผ่านพารามิเตอร์ (parameters) และฟังก์ชันคืนผลลัพธ์ได้ด้วยคำสั่ง return ฟังก์ชันช่วยให้โค้ดสั้นลงและไม่ต้องเขียนขั้นตอนเดิมซ้ำ
ประเด็นสำคัญ
- def
greet(name): defines a function;greet("Grace")calls it. - Parameters receive the values passed in the call.
- return sends a result back; without it the function returns None.
- Default values make parameters optional: def
greet(name, course="Python").
ใช้เมื่อไร?
- เรียนรู้ไวยากรณ์และแนวคิดพื้นฐานของ Python ผ่านตัวอย่างสั้น ๆ ที่เข้าใจง่าย
- สร้างพื้นฐานที่มั่นคงก่อนไปต่อกับโจทย์ที่ซับซ้อนขึ้น
- รันโค้ดในเบราว์เซอร์ได้ทันทีโดยไม่ต้องติดตั้ง Python บนเครื่อง
โค้ดตัวอย่าง
def greet(name, language="Python"):
return f"Hello, {name}! Welcome to {language}."
message = greet("Grace")
print(message)
ผลลัพธ์จากการรัน
Hello, Grace! Welcome to Python.
อธิบายโค้ด
ฟังก์ชัน greet() มีพารามิเตอร์ language ซึ่งมีค่าเริ่มต้นเป็น "Python" จึงไม่ต้องส่งค่านี้เมื่อเรียก greet("Grace") ฟังก์ชันไม่ได้พิมพ์เอง แต่คืนสตริงกลับมา โค้ดที่เรียกใช้จึงเลือกได้อิสระว่าจะเก็บ แสดง หรือนำผลลัพธ์ไปประมวลผลต่อ
เปลี่ยนค่าและรันโปรแกรมด้วย คอมไพเลอร์ Python ออนไลน์ของ CodeUtility โดยไม่ต้องติดตั้ง Python
แบบฝึกหัดเพิ่มเติม
ลองแก้โค้ดตามคำแนะนำด้านล่าง การเปลี่ยนโค้ดแล้วดูผลลัพธ์จะช่วยให้เข้าใจบทเรียนได้ดีกว่าการอ่านอย่างเดียวมาก
- เปลี่ยนข้อมูลอินพุตแล้วทายผลลัพธ์ก่อนรัน
- เพิ่มการตรวจสอบข้อมูลว่างหรือข้อมูลที่ไม่ถูกต้อง
- แยกขั้นตอนการประมวลผลเป็นฟังก์ชันและทดสอบกับข้อมูลหลายชุด
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- Rectangle Perimeter Compute the perimeter of a rectangle from its sides. ง่าย
- Distance Between Points Compute the straight-line distance between two points. ง่าย
- Days in a Month Return how many days a month has, including leap years. ง่าย