Python รองรับ mathematics logical conditions ดังนี้
- เท่ากับ: a == b
- ไม่เท่ากับ: a != b
- น้อยกว่า: a < b
- น้อยกว่าหรือเท่ากับ: a <= b
- มากกว่า: a > b
- มากกว่าหรือเท่ากับ: a >= b
conditions เหล่านี้สามารถนำไปใช้ได้หลากหลาย แต่การนำไปใช้ที่บ่อยที่สุดคือ การใช้ใน if statements และ loops
การเขียนเปรียบเทียบโดยใช้ if statement และ operators (conditions) เหล่านี้เรียกว่า ternary operators หรือ conditional expressions
Conditional expressions
if statement
สามารถเขียนได้โดยใช้คึเวิร์ด if นำหน้า ตามด้วย condition และเครื่องหมาย colon
เช่น
a = 2
b = 4
if a < b:
print(‘b is greater than a’)
ย่อหน้าหรือ Indentation
Python จำเป็นต้องใช้การย่อหน้าในการกำหนด scope ในโค้ดบล็อก (จะใช้ tab ที่อยู่ซ้ายมือด้านบนหรือกดเว้นวรรค 2 ครั้งก็ได้) หากไม่ใส่ย่อหน้า เมื่อรันโปรแกรม จะเกิด error
elif
เป็นคีย์เวิร์ดที่ใช้ต่อจาก if statement หาก condition หรือเงื่อนไขที่ให้ไว้ก่อนหน้านี้ไม่เป็นจริง เช่น
a = 10
b = 5
if a < b:
print(‘b is greater than a’)
elif a > b:
print(‘a is greater than b’)
else
เป็นคีย์เวิร์ดที่ใช้สำหรับเงื่อนไขอันสุดท้าย หากเงื่อนไขอื่นๆทั้งหมดที่กล่าวไปแล้วไม่เป็นจริง การเขียน else statement ไม่ต้องใส่เงื่อนไข สามารถใส่ colon แล้วเคาะบรรทัดใหม่เพื่อเขียน consequence ได้เลย เช่น
a = 20
b = 20
if a > b:
print(‘a is greater than b’)
if a < b:
print(‘b is greater than a’)
else:
print(‘They are equal’)
สามารถใช้ else โดยไม่ต้องใช้ elif ได้ เช่น
a = 10
b = 5
if a < b:
print(‘b is greater than a’)
else:
print(‘a is greater than b’)
การเขียนแบบ short hand
การเขียนแบบ short hand คือการเขียนทุกอย่างให้อยู่ในบรรทัดเดียว
if แบบ short hand
if a < b: print(‘a is less than b’)
if…else แบบ short hand
เริ่ม consequence ก่อน จากนั้นตามด้วย if statement และ เงื่อนไข
หากมีมากกว่าหนึ่งเงื่อนไข เงื่อนไขที่สองให้ใช้ else statement ตามด้วย consequence + if statement + เงื่อนไข
สำหรับ else สุดท้าย สามารถจบแค่ else + consequence ได้เลย
a = 13
b = 13
print('a is greater') if a > b else print('equal') if a == b else print('b is greater')
การใช้ logical operators ใน conditional expressions
and
คีย์เวิร์ดที่ใช้รวมประโยคเงื่อนไขสองอันเข้าด้วยกัน โดยเงื่อนไขทั้งคู่ต้องเป็นจริง เช่น
a = 2
b = 5
c = 6
if b > a and c > a:
print(‘b and c are greater than a’)
or
คีย์เวิร์ดที่ใช้เลือกประโยคเงื่อนไขใดเงื่อนไขหนึ่ง โดยเงื่อนไขอย่างน้อยหนึ่งเงื่อนไขในเงื่อนไขทั้งหมดต้องเป็นจริง เช่น
a = 2
b = 5
c = 6
if b > a c == a:
print(‘one condition is true’)
Nested if
คือการใส่ if statement ใน scope ของ if statement เรียกว่า nested if statement
เช่น
x = 9
if x > 10:
print(‘x is greater than 10')
if x > 15:
print(‘, also greater than 15')
else:
print(‘, but not greater than 15')
else:
print(‘x is less than 10’)
Output:
x is less than 10
pass statement
ปกติแล้ว if statement จะว่างไม่ได้ คือต้องมีเงื่อนไขและคำสั่งเมื่อเงื่อนไขเป็นจริง แต่หากมีเรามีเหตุผลอะไรก็ตามที่จะต้องปล่อยให้มันว่างไปก่อน หรือ ต้องเขียนอย่างอื่นก่อนแล้วจะกลับมาทำ if statement ทีหลัง เราสามารถใส่ pass statement ใน block scope เพื่อป้องกันการเกิด error