เงื่อนไข if elif else ใน Python
เงื่อนไขช่วยให้โปรแกรมเลือกว่าจะทำอะไร: Python จะตรวจ if หรือ elif ทีละอันตามลำดับ และรันบล็อกแรกที่เงื่อนไขเป็น True
เงื่อนไข if elif else ใน Python คืออะไร?
เงื่อนไขช่วยให้โปรแกรมเลือกว่าจะทำอะไร: Python จะตรวจ if หรือ elif ทีละอันตามลำดับ และรันบล็อกแรกที่เงื่อนไขเป็น True
ตัดสินใจด้วย if, elif และ else และรวมเงื่อนไขด้วย and, or และ not
ควรใช้เมื่อใด?
- เรียนรู้ไวยากรณ์ Python ผ่านโค้ดที่รันได้
- สร้างพื้นฐานสำหรับโจทย์ที่ซับซ้อนขึ้น
- ทดลองแนวคิดโดยไม่ต้องติดตั้งบนเครื่อง
ดูการทำงาน
เลื่อนแถบเพื่อเปลี่ยนคะแนน ผังงานจะไฮไลต์เส้นทางที่โปรแกรมเดินผ่าน และบรรทัดโค้ดที่ตรงกันจะถูกเน้น
โค้ดตัวอย่าง
temperature = 23
# if / elif / else picks the first branch whose condition is True.
if temperature >= 30:
print("It's hot")
elif temperature >= 20:
print("It's warm")
elif temperature >= 10:
print("It's cool")
else:
print("It's cold")
# and, or, not combine conditions.
age = 17
has_ticket = True
if age >= 18 and has_ticket:
print("You can enter")
elif not has_ticket:
print("Please buy a ticket")
else:
print("You need an adult with you")
# A conditional expression chooses between two values on one line.
number = 7
kind = "even" if number % 2 == 0 else "odd"
print(number, "is", kind)
ผลลัพธ์ที่คาดหวัง
It's warm
You need an adult with you
7 is odd
หลักการทำงาน
การย่อหน้าแสดงว่าบรรทัดไหนอยู่ในแต่ละทางเลือก and, or และ not ใช้สร้างเงื่อนไขที่ซับซ้อนขึ้น และ value_if_true if condition else value_if_false ใช้เลือกค่าบนบรรทัดเดียว
เปลี่ยนค่าและรันโปรแกรมด้วย คอมไพเลอร์ Python ออนไลน์ของ CodeUtility โดยไม่ต้องติดตั้ง Python
แบบฝึกหัด
ลองเปลี่ยน input และทดสอบกรณีขอบก่อนใช้ชุดข้อมูลที่ใหญ่ขึ้น
- คาดเดา output ก่อนรัน
- รองรับ input ว่างหรือไม่ถูกต้อง
- แยก logic เป็นฟังก์ชันและเพิ่ม test case
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- Letter Grade Turn a test score into a letter grade. ง่าย
- Largest of Three Pick the largest of three numbers without a built-in max. ง่าย
- Ticket Price by Age Choose a cinema ticket price from the visitor's age. ง่าย