Control Structures Structure: โครงสร้างควบคุมการทำงาน
How Python changes the top-to-bottom order of a program Python เปลี่ยนลำดับการทำงานจากบนลงล่างของโปรแกรมได้อย่างไร
Overview ภาพรวม
By default, Python runs a program one line at a time, from the first line to the last. That is enough
for a program that always does the same steps, but most useful programs have to react to their data:
skip a step, choose between two answers, or repeat a job until it is finished. A control structure is a
statement that changes this top-to-bottom order. Most of them depend on a condition, an expression that
gives True or False — the Boolean values from
04_Booleans. The header line of a structure ends with a colon, and the
indented lines under it form the block that the structure controls.
โดยปกติ Python จะทำงานทีละบรรทัด จากบรรทัดแรกลงไปจนถึงบรรทัดสุดท้าย ซึ่งเพียงพอสำหรับโปรแกรมที่ทำขั้นตอนเดิมทุกครั้ง
แต่โปรแกรมส่วนใหญ่ต้องทำงานตามข้อมูลที่ได้รับ เช่น ข้ามบางขั้นตอน เลือกระหว่างสองคำตอบ หรือทำงานเดิมซ้ำจนเสร็จ
โครงสร้างควบคุม (control structure) คือคำสั่งที่เปลี่ยนลำดับการทำงานจากบนลงล่างนี้
โครงสร้างควบคุมส่วนใหญ่ขึ้นอยู่กับเงื่อนไข (condition) ซึ่งเป็นนิพจน์ที่ให้ค่า True หรือ False
(ค่าบูลีนจากบท 04_Booleans)
บรรทัดแรกของโครงสร้างจะลงท้ายด้วยเครื่องหมาย : และบรรทัดที่ย่อหน้าเข้าไปด้านล่างคือ block ที่โครงสร้างนั้นควบคุม
How to choose a structure เลือกใช้โครงสร้างไหนดี
Ask these questions about the problem before you start typing:
แนะนำให้ถามคำถามเหล่านี้กับโจทย์ก่อนเริ่มเขียนโค้ด:
- Should the program take one of several paths, depending on a condition? Use
if, withelifandelsefor the other paths. - Is one value compared with a few fixed values, such as a menu choice or a command word? One
matchwith acasefor each value is easier to read than a long chain ofelif. - Could a step fail for a reason outside your code, such as a user typing letters where a number is
expected, or a file that does not exist? Put that step inside
tryand handle the failure inexcept. - Do you know how many times to repeat, or do you have a sequence of items to visit one by one? Use
for. - Does the repetition stop only when something happens, and you cannot tell in advance when? Use
while.
- โปรแกรมต้องเลือกทำทางใดทางหนึ่งตามเงื่อนไขหรือไม่
ถ้าใช่ ใช้ifและใช้elifกับelseสำหรับทางอื่น - ต้องเทียบค่าเดียวกับค่าคงที่หลายค่าหรือไม่ เช่น ตัวเลือกในเมนู หรือคำสั่งที่ผู้ใช้พิมพ์ ใช้
matchแล้วเขียนcaseหนึ่งอันต่อหนึ่งค่า จะอ่านง่ายกว่าelifต่อกันยาวๆ - มีขั้นตอนที่อาจล้มเหลวด้วยสาเหตุนอกโค้ดของเราหรือไม่ เช่น ผู้ใช้พิมพ์ตัวอักษรในช่องที่ต้องเป็นตัวเลข
หรือไฟล์ที่ต้องเปิดไม่มีอยู่ ให้ใส่ขั้นตอนนั้นไว้ใน
tryแล้วจัดการความผิดพลาดในexcept - รู้จำนวนรอบที่ต้องทำซ้ำ หรือมีข้อมูลเป็นลำดับที่ต้องไล่ทีละตัวหรือไม่
ถ้าใช่ ใช้for - การทำซ้ำจะหยุดก็ต่อเมื่อเกิดเหตุการณ์บางอย่าง และบอกล่วงหน้าไม่ได้ว่าเมื่อไรหรือไม่
ถ้าใช่ ใช้while
Combining structures การใช้โครงสร้างร่วมกัน
Real programs rarely use one structure alone. A structure can sit inside the block of another one; this is called nesting, and the inner block is indented one more level.
โปรแกรมจริงไม่ค่อยใช้โครงสร้างเพียงแบบเดียว โครงสร้างหนึ่งสามารถอยู่ใน block ของอีกโครงสร้างหนึ่งได้ เรียกว่าการซ้อน (nesting) และ block ด้านในจะย่อหน้าเข้าไปอีกหนึ่งระดับ
1 for + if
The for loop visits each reading in turn, and the if inside it decides what to
print for that reading. The if runs once in every pass of the loop, so five readings give
five lines.
for จะไล่ค่าที่อ่านได้ทีละค่า และ if ที่อยู่ข้างในจะตัดสินว่าจะพิมพ์อะไรสำหรับค่านั้น
if ทำงานหนึ่งครั้งในทุกรอบของ loop ค่าที่อ่านได้ 5 ค่าจึงได้ผลลัพธ์ 5 บรรทัด
12 is OK 35 is too high 7 is OK 41 is too high 28 is OK
2 while + try
Here a while loop keeps asking until the text can be turned into a whole number.
int() converts text to an integer and raises a ValueError for text such as
abc or 4.5; except ValueError catches it, prints a message, and
the loop asks again. When the conversion works, break leaves the loop at once. The
[input] box holds the three values typed in this example.
ตัวอย่างนี้ใช้ while ถามซ้ำไปเรื่อยๆ จนกว่าข้อความที่ป้อนจะแปลงเป็นจำนวนเต็มได้
int() แปลงข้อความเป็นจำนวนเต็ม และจะเกิด ValueError เมื่อข้อความเป็นแบบ
abc หรือ 4.5 ส่วน except ValueError จะดักจับ error นั้น
พิมพ์ข้อความแจ้ง แล้ว loop ก็ถามใหม่ เมื่อแปลงได้สำเร็จ break จะออกจาก loop ทันที
ช่อง [input] เก็บค่า 3 ค่าที่ป้อนในตัวอย่างนี้
Enter a whole number: abc Not a whole number, try again Enter a whole number: 4.5 Not a whole number, try again Enter a whole number: 12 You entered 12
Common mistakes ข้อผิดพลาดที่พบบ่อย
- Missing colon. Forgetting the
:at the end of a header line such asif x > 0is a syntax error, so the program does not start at all. - Wrong indentation. If a line that belongs to a block is not indented, Python reports
an
IndentationError— or, worse, the program runs but that line sits outside the loop and runs only once. - A
whileloop that never stops. If nothing in the loop body changes the condition, it staysTrueforever. Check that everywhileloop updates its variable or reaches abreak. - No
elseorcase _. Without a finalelseorcase _, a value you did not expect passes through silently and the program prints nothing. A default branch makes the unexpected case visible. - An
exceptthat is too broad. A bareexcept:also hides mistakes in your own code, such as a misspelt variable name. Catch the error you expect, for exampleValueError.
- ลืมเครื่องหมาย
:ถ้าลืม:ท้ายบรรทัดหัว เช่นif x > 0จะเกิด syntax error และโปรแกรมจะไม่เริ่มทำงานเลย - ย่อหน้าผิด ถ้าบรรทัดที่ควรอยู่ใน block ไม่ได้ย่อหน้า Python จะแจ้ง
IndentationErrorหรือแย่กว่านั้นคือโปรแกรมรันได้ แต่บรรทัดนั้นอยู่นอก loop และทำงานแค่ครั้งเดียว whileที่ไม่หยุด ถ้าไม่มีคำสั่งใดใน loop ที่ทำให้เงื่อนไขเปลี่ยน เงื่อนไขจะเป็นTrueตลอดไป ให้ตรวจว่าทุกwhileมีการเปลี่ยนค่าตัวแปร หรือไปถึงbreakได้- ไม่มี
elseหรือcase _ถ้าไม่มีelseหรือcase _ปิดท้าย ค่าที่ไม่ได้คาดไว้จะผ่านไปเงียบๆ และโปรแกรมไม่แสดงอะไรเลย การมีทางเลือกปิดท้าย (default) ทำให้เห็นกรณีที่ไม่ได้คาดไว้ exceptที่กว้างเกินไปexcept:ที่ไม่ระบุชนิดจะซ่อนความผิดพลาดในโค้ดของเราเองด้วย เช่น สะกดชื่อตัวแปรผิด ให้ดักจับเฉพาะ error ที่คาดไว้ เช่นValueError
Learning order ลำดับการเรียน
Work through the lessons below in their numbered order. The decision structures come first, then error
handling, then the two loops, because the loop examples use if inside the loop body. After
this section, continue with 10_Data_Files, where a for loop
goes through the lines of a text file one by one.
เรียนบทเรียนด้านล่างตามลำดับหมายเลข เริ่มจากโครงสร้างการตัดสินใจ ต่อด้วยการจัดการความผิดพลาด แล้วจึงเป็น loop ทั้งสองแบบ
เพราะตัวอย่างของ loop มี if อยู่ข้างใน หลังจบหมวดนี้ให้เรียนต่อที่
10_Data_Files ซึ่งใช้ for ไล่อ่านบรรทัดในไฟล์ข้อความทีละบรรทัด