[Python] EP 10: Conditional Statement

Master
Artisan Brain Academy
1 min readOct 21, 2019
If-Else statement

สวัสดีครับ วันนี้เราจะมาพูดถึงเรื่องการเขียนรูปประโยคเงื่อนไข ​(if-else statement) ซึ่งเอาไว้ใช้เมื่อมีเหตุการณ์ ตั้งแต่ 1 กรณี ที่มีเงื่อนไขจะทำก็ต่อเมื่อข้อมูลนั้นตรงกับที่เราต้องการ เรามาลองดูตัวอย่างกันนะครับ

เราจะใช้รูปประโยค if … else โดยหากมีกรณีที่มากกว่า 2 อย่างต้องตรวจสอบให้ใช้ elif (else if) เข้ามาช่วยเพิ่มเงื่อนไขให้มากขึ้น

if เงื่อนไข:
statement
elif เงื่อนไข:
statement
else:
statement

ตัวอย่างที่ 1

go_to_thailand_before = True
if go_to_thailand_before:
print("Don't buy flight-ticket")
else:
print("Do buy flight-ticket")

ตัวอย่างที่ 2

go_to_thailand_before = True
go_to_bangkok_before = False
if go_to_thailand_before:
print("Don't buy flight-ticket")
else:
if go_to_bangkok_before:
print("Don't buy flight-ticket")
else:
print("Do buy flight-ticket")

ตัวอย่างที่ 3

score = 67
if score > 80:
print('Grade A')
elif score > 70:
print('Grade B')
elif score > 60:
print('Grade C')
else:
print('Grade D')

หวังว่าจะพอเป็นแนวทางในการฝึกเขียน python ครับ หากอยากแสดงความคิดเห็นสามารถติดต่อได้ทาง Facebook หรือ FB Page น้อมรับทุกการแสดงความคิดเห็น

Happy Coding!!!!

--

--