Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

สวิตช์เคสใน Python (แทนที่)


ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่ทำหน้าที่เป็นตัวพิมพ์สลับใน Python

ภาษาโปรแกรมอื่นๆ เช่น C, C++, Java ฯลฯ มีสวิตช์ในขณะที่ Python ไม่. มาเขียนโปรแกรมที่ทำหน้าที่เป็น switch case ใน Python กันเถอะ

เราจะใช้โครงสร้างข้อมูล dict เพื่อเขียน switch case ใน Python มาดูโค้ดต่อไปนี้กัน

ตัวอย่าง

# dictionary with keys and values
days = {
   0: 'Sunday',
   1: 'Monday',
   2: 'Tuesday',
   3: 'Wednesday',
   4: 'Thursday',
   5: 'Friday',
   6: 'Saturday'
}
# we will use 'get' method to access the days
# if we provide the correct key, then we will get the corresponding value
# if we provide a key that's not in the dictionary, then we will get the defaul
lue
print(days.get(0, 'Bad day'))
print(days.get(10, 'Bad day'))

ผลลัพธ์

หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้

Sunday
Bad day

เราสามารถวางอะไรก็ได้แทนค่า ค่าเริ่มต้นของ รับ วิธีการแสดงถึง ค่าเริ่มต้น คีย์เวิร์ดในกรณีสวิตช์

บทสรุป

หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น