Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Toán Tử So Sánh (Comparison Operators) trong Python

Các toán tử so sánh (còn gọi là toán tử quan hệ) so sánh hai giá trị và trả về kết quả boolean. Giả sử a = 10, b = 20:

STT Toán tử & Mô tả Ví dụ
1== - Bằng nhau(a == b) là False
2!= - Khác nhau(a != b) là True
3<> - Khác nhau (cũ, Python 2)(a <> b) là True
4> - Lớn hơn(a > b) là False
5< - Nhỏ hơn(a < b) là True
6>= - Lớn hơn hoặc bằng(a >= b) là False
7<= - Nhỏ hơn hoặc bằng(a <= b) là True

Ví dụ chương trình

#!/usr/bin/python
a = 21
b = 10

if a == b:  print("Line 1 - a is equal to b")
else:       print("Line 1 - a is not equal to b")

if a != b:  print("Line 2 - a is not equal to b")
else:       print("Line 2 - a is equal to b")

if a <> b:  print("Line 3 - a is not equal to b")  # Python 2
else:       print("Line 3 - a is equal to b")

if a < b:   print("Line 4 - a is less than b")
else:       print("Line 4 - a is not less than b")

if a > b:   print("Line 5 - a is greater than b")
else:       print("Line 5 - a is not greater than b")

a, b = 5, 20
if a <= b:  print("Line 6 - a is either less than or equal to b")
if b >= a:  print("Line 7 - b is either greater than or equal to a")

Kết quả

Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to a

Lưu ý: Toán tử <> đã bị loại bỏ trong Python 3, hãy dùng !=.