ใน Python ตัวดำเนินการตรรกะ and, or, not ใช้กับ String ได้ โดย String ว่าง "" ถือเป็น False ส่วน String ที่มีค่า ถือเป็น True
พฤติกรรมของ and และ or
| นิพจน์ | ผลลัพธ์ |
|---|---|
x and y | ถ้า x เป็น False คืน y, ไม่เช่นนั้นคืน x |
x or y | ถ้า x เป็น True คืน x, ไม่เช่นนั้นคืน y |
not x | True ถ้า x เป็น False, มิฉะนั้น False |
ตัวอย่างโค้ด
str1 = ""
str2 = "python"
print(repr(str1 and str2)) # ''
print(repr(str2 and str1)) # ''
print(repr(str1 or str2)) # 'python'
print(repr(str2 or str1)) # 'python'
str1 = "Hello "
print(repr(str1 and str2)) # 'python'
print(repr(str2 and str1)) # 'Hello '
print(repr(str1 or str2)) # 'Hello '
print(repr(str2 or str1)) # 'Hello '
print(repr(not str1)) # False
str2 = ""
print(repr(not str2)) # True
str2 = "hello"
print("Hello == hello:", str1 == str2) # False
ผลลัพธ์
''
''
'python'
'python'
'python'
'Hello '
'Hello '
'python'
False
True
Hello == hello: False
จุดสำคัญ
andคืน ตัวแรกที่เป็น False (หรือตัวสุดท้ายถ้าทั้งคู่ True)orคืน ตัวแรกที่เป็น True (หรือตัวสุดท้ายถ้าทั้งคู่ False)- ไม่ได้คืนแค่ True/False แต่คืน ค่าจริงของตัวแปร นั้นเอง
- เทคนิคนี้ใช้กันมากในการกำหนดค่า default:
val = user_input or "default"