ผลต่างระหว่างรุ่นของ "วิธีคิดแบบนักวิทยาการคอมพิวเตอร์/Functions"

เนื้อหาที่ลบ เนื้อหาที่เพิ่ม
Kaitok1112 (คุย | ส่วนร่วม)
Kaitok1112 (คุย | ส่วนร่วม)
บรรทัดที่ 335:
แต่ละฟังก์ชันถูกทำหน้าที่โดย frame โดย frame คือ กล่องซึ่งมีชื่อของฟังก์ชันอยู่ด้านข้าง และ มีพารามิเตอร์และตัวแปรของฟังก์ชันอยู่ด้านใน ลักษณะตัวอย่าง stack diagram
[[ภาพ:ch3.jpg|center]]
คำสั่งของ stack แสดง flow of execution โดย printTwice ถูกเรียกโดย catTwice และ catTwice ถูกเรียกโดย __main__ ซึ่งเป็นชื่อพิเศษสำหรับฟังก์ชันสูงสุด เมื่อคุณสร้างตัวแปรภายนอกฟังก์ชันใดๆ มันจะเป็นของ __main__
 
แต่ละพารามิเตอร์อ้างอิงถึงค่าที่เหมือนกัน เช่นเดียวกับ argument ที่เหมือนกัน ดังนั้น part 1 มีค่าเหมือนกับ chant 1 , part 2 มีค่าเหมือนกับ chant 2 และ bruce มีค่าเหมือนกับ cat
 
ถ้าเกิด error ระหว่างการเรียกใช้ฟังก์ชัน python จะพิมพ์ค่าชื่อของฟังก์ชันและชื่อของฟังก์ชันที่เรียกมัน และชื่อของฟังก์ชันที่เรียกอีกทีหนึ่ง โดยทุกอย่างจะกลับไปสู่ __main__
 
ตัวอย่างเช่น ถ้าพวกเราลองเข้าไปยัง cat จากการ printTwice พวกเราจะได้ NameError
 
Traceback (innermost last):
 
File "test.py", line 13, in __main__
 
catTwice(chant1, chant2)
 
File "test.py", line 5, in catTwice
 
printTwice(cat)
 
File "test.py", line 9, in printTwice
 
print cat
 
NameError: cat
 
list ของฟังก์ชันนี้ถูกเรียกว่า traceback มันบอกคุณว่าไฟล์ของโปรแกรมเกิด error อะไร ที่บรรทัดไหน และฟังก์ชันอะไรที่กำลัง execute อยู่ที่เวลานั้น มันจะแสดงบรรทัดที่เป็นเหตุของการเกิด error
 
สังเกตถึงความเหมือนระหว่าง traceback และ stack diagram มันจะไม่เกิดขึ้นพร้อมกัน
===3.12 Functions with results===
คุณอาจจะสังเกตบางอย่างของฟังก์ชันที่เรากำลังใช้อยู่ เช่น ฟังก์ชัน math ถูกแทนที่ด้วยผลลัพธ์ ฟังก์ชันอื่นๆ เช่น newLine แสดงการกระทำออกมา แต่ไม่มีการ return ค่า จึงยกคำถามเหล่านี้ขึ้นมา
 
- จะเกิดอะไรขึ้นถ้าเราเรียกฟังก์ชัน และไม่ได้ผลลัพธ์อะไรออกมา ?
 
- เกิดอะไรขึ้นถ้าคุณใช้ฟังก์ชันโดยปราศจากผลลัพธ์ที่เป็นส่วนหนึ่งของ expression เช่น newLine() + 7 ?
 
- คุณสามารถเขียนฟังก์ชันที่หาค่าผลลัพธ์ หรือ คุณติดกับฟังก์ชันทั่วไปเช่น newLine และ printTwice ?
===3.13 Glossary===
function call: A statement that executes a function. It consists of the name of the function followed by a list of arguments enclosed in parentheses.
 
argument: A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
 
return value: The result of a function. If a function call is used as an expression, the return value is the value of the expression.
 
type conversion: An explicit statement that takes a value of one type and computes a corresponding value of another type.
 
type coercion: A type conversion that happens automatically according to Python's coercion rules.
 
module: A file that contains a collection of related functions and classes.
 
dot notation: The syntax for calling a function in another module, specifying the module name followed by a dot (period) and the function name.