Procedures & functions
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
A function is a named block
- A function is a named block of code you can run again and again.
- Define it once with
def, then call it by name. - This avoids repeating yourself and keeps programs tidy.
English
def greet():
print("Hello!")
greet()
greet()
English
Parameters pass data in
- A parameter is a value the function receives.
- Put it in the brackets, and pass an argument when you call.
- Keep the number of parameters small so the function stays easy to read.
English
def greet(name):
print("Hello, " + name)
greet("Ada")
greet("Sam")
English
Functions return a value
- A function hands a value back with
return. - A block that only does something and returns nothing is a procedure.

English
def square(n):
return n * n
answer = square(6)
print(answer) # 36
สำรวจ
Call and return
Calling runs the function's body; return hands a value back.
English
In the exam: PROCEDURE and FUNCTION
- Pseudocode separates a
PROCEDURE(no result) from aFUNCTION(returns a value).
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
English
Common mistakes
- A function returns a value with
return; a procedure just does a job. - Call it with
(). - Parameters receive the arguments in order.
English
Now you try
- Write each function — it is then called for you in the check.
- Press Check answer to test your code.
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a function double(n) that ผลตอบแทน n times 2.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a function is_even(n) that returns True when n is even, otherwise False.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a procedure print_stars(n) that prints a line of n star (*) characters, then call it with 4 so it prints ****.
คลิก Run เพื่อดูผลลัพธ์ที่นี่