13 มิถุนายน 2558

Published มิถุนายน 13, 2558 by with 0 comment

ทำไมภาษา Python จึงไม่มี switch case

ทำไมภาษา Python จึงไม่มี switch case เป็นที่รู้กันดีว่าภาษา Python ไม่มี switch case เหมือนในภาษาอื่น ๆ

ที่จริงแล้ว Guido van Rossum บิดาภาษา Python ได้มีการเสนอให้มี switch case บนภาษา Python 3.0 ในงาน PyCon 2007 อ่านได้ที่ PEP 3103 -- A Switch/Case Statement  แต่ไม่เป็นที่ยอมรับ จึงปฏิเสธไป ไม่นำ switch case เข้ามารวมในภาษา Python ผมคิดว่าอาจเป็นเพราะภาษา Python มีตัวแปรชนิดข้อมูลอื่น ๆ ที่สามารถทดแทน switch case ได้ เช่น dictionary และโค้ดสะอาดกว่า ดูง่ายกว่า switch case ตามสไตล์ภาษา Python

เราสามารถใช้ข้อมูลชนิด dictionary ทดแทน switch case ได้ง่าย ๆ ดังนี้ครับ

[c]
a = 0;
switch(a)
{
case 0:
printf("0");
break;

case 1:
printf("1");
break;

case 2:
printf("2");
break;
case.default:
printf("?");
}
[/c]

นำมาแปลงเป็นข้อมูลชนิด dictionary ในภาษา Python โดยใช้ฟังก์ชันเข้ามาช่วย

[python]
a = 0
def f(x):
return {
0: 0,
1: 1,
2: 2,
}.get(x, "?") # 9 เป็นค่า default ถ้าค่า x ไม่ตรงกับค่าใดเลย
print(f(a))
[/python]

ผลลัพธ์
0

จะเห็นได้ว่า ข้อมูลชนิด dictionary ทดแทนคำสั่งเงื่อนไข switch case ได้และเข้าใจง่ายกว่า switch case ครับ

อ่านเพิ่มเติม ข้อมูลชนิด dictionary ในภาษา Python

ถ้าใครอยากใช้ switch case จริง ๆ สามารถเขียนคำสั่งเงื่อนไข switch case บนภาษา Python ได้ โดยใช้โมดูล switch ครับ ใช้ License: BSD License รองรับทั้ง Python 2 และ Python 3

สามารถติดตั้งได้โดยใช้คำสั่ง pip
pip install switch

ในการใช้งานโมดูล switch ต้อง

[python]
from switch import Switch[/python]

เข้ามาทุกครั้ง และ ใช้ with คู่กับคำสั่ง switch ตามตัวอย่างต่อไปนี้ครับ

[python]
from switch import Switch
val = 0
with Switch(val) as case:
if case(0):
print("0")
if case.default:
print("1")
[/python]

ผลลัพธ์
0

นำมาใช้กับสตริง

[python]
from switch import Switch
val = "hi"
with Switch(val) as case:
if case("hi"):
print("Hello :)")
if case.default:
print("?")
[/python]

ผลลัพธ์
Hello :)

อ้างอิง

ติดตามบทความต่อไปนะครับ
ขอบคุณครับ

0 ความคิดเห็น:

แสดงความคิดเห็น

แสดงความคิดเห็นได้ครับ :)