Python Не рівні Operaтор (!=)

⚡ Розумний підсумок

Python not equal operators compare two operands and return a Boolean value when their contents differ. The != symbol works in Python 2 and 3, and because Python is dynamically typed, it compares values across different data types too.

  • 🔘 Визначення: The not equal operator returns True when two operands hold different values and False when they match.
  • ☑️ Two symbols: Python provides != for every version and the older <> form, which runs only under Python 2.
  • Boolean result: Each comparison evaluates to a Boolean, making the operator ideal for conditions and validation checks.
  • 🧪 Dynamic typing: Тому що Python is strongly and dynamically typed, != can compare an integer, a float, and a string safely.
  • 🛠️ Потік керування: Pairing != with if statements and while loops filters data, such as isolating even or odd numbers.
  • Custom objects: Overriding the __ne__ method lets a class define exactly how the not equal operator behaves.

Python Не рівні Operaтор

Що таке Python Не дорівнює Operaтор?

Python ідентифікується як мова програмування, яка є дуже динамічною, і зазвичай розглядається як строго типізована мова. Це твердження можна пояснити розумінням значення оператора нерівності. в not equal якщо значення двох операндів по обидві сторони оператора не рівні, тоді оператор надає істинне значення, інакше — хибне.

In not equal operator, if two variables are of different types but hold the same values in themselves, then the not equal operator returns a true. Not many programming languages can classify it as true if the variable type is of a different type, which makes Python a very dynamic language. In Python, not equal operators can be classified as one of the comparison operators.

Типи Не дорівнюють операторам із синтаксисом in Python

Синтаксис обох типів показано нижче: –

X<>Y

X!=Y

There are two types of not equal operators in Python:-

  • !=
  • <>

Перший тип, != використовується в Python версії 2 і 3.

Другий тип, <> використовується в Python version 2, and under version 3, this operator is deprecated.

Приклад Python Не рівні Operaтор

Давайте розглянемо два сценарії, щоб проілюструвати нерівність у python. Нижче наведено приклад оператора нерівності для одного типу даних, але різних значень:-

A = 44
B = 284
C = 284
print(B!=A)
print(B!=C)

вихід:

True
False

Нижче наведено приклад нерівності в python для різних типів даних, але однакових значень

C = 12222
X = 12222.0
Y = "12222"
print(C!=X)
print(X!=Y)
print(C!=Y)

вихід:

False
True
True

Як використовувати Not Equal Operator з інструкцією IF

У Python інструкцію if можна описати як інструкцію, яка перевіряє умову початкового рівня та виконується, коли вона виконується.

Розглянемо базовий приклад використання оператора if і не дорівнює оператору, як показано нижче: –

X = 5
Y = 5
if ( X != Y ):
  print("X is not equal to Y")
else:
  print("X is equal to Y")

вихід:

X is equal to Y

Тут не дорівнює != використовується разом із оператором if.

Як використовувати оператор дорівнює (==) з циклом while

У Python цикл while повторює блок коду, доки умова є істинною чи хибною. Розглянемо випадок друку непарних чисел за допомогою циклу while і оператора дорівнює, як показано нижче: –

m = 300
while m <= 305:
   m = m + 1
  if m%2 == 0:
     continue
   print (m)

вихід:

301
303
305

Тут дорівнює == використовується разом із оператором if.

Приклад: пошук парних чисел за допомогою оператора нерівності

У Python цикл while також можна використовувати з оператором not equivalent. Розглянемо випадок друку парних чисел за допомогою циклу while і не дорівнює оператору, як показано нижче: –

m = 300
while m <= 305:
  m = m + 1
  if m%2 != 0:
    continue
  print (m)

вихід:

302
304
306

Тут не дорівнює != використовується разом із оператором if.

як використовувати Python не рівні Operator із настроюваним об’єктом

Користувацькі об’єкти дозволяють користувачеві або розробнику створювати власні реалізації. Це дозволяє розробникам змінювати фактичні результати, ніж зазвичай очікується.

Розглянемо приклад спеціального об’єкта, який використовує оператор not equal to , як показано нижче: –

приклад:

class G9Example:

   s_n=''

def __init__(self, name):

   self.s_n = name

def __ne__(self, x):

if type(x) != type(self):

  return True

# return True for different values

if self.s_n != x.s_n:

  return True

else:

  return False

G1 = G9Example("Guru99")

G2 = G9Example("HipHop99")

G3 = G9Example("Guru99")

print(G1 != G2)

print(G2 != G3)

print(G1 != G3)

вихід:

True

True

False

Оператори порівняння в Python

Наступна таблиця описує список для порівняння оператори в Python: -

Operaтор Сенс Приклад
!= Не дорівнює - дає істину, якщо операнди не мають однакових значень A!=B
== Дорівнює – дає істину, якщо операнди мають однакові значення A==B
>= Більше або дорівнює – дає значення true, якщо перший операнд більший або дорівнює другому операнду A>=B
<= Less ніж або дорівнює - дає значення true, якщо перший операнд є Less ніж або дорівнює другому операнду A<=B
> Більше – дає значення true, якщо перший операнд більший за другий A>B
< Less ніж – дає значення true, якщо перший операнд є Less ніж другий операнд A<B

Корисні поради щодо використання Not Equal Operaтор

Ось кілька корисних порад

  • Оператор не дорівнює можна використовувати у форматованих рядках.
  • Ця функція відносно нова і є частиною Python версія 3.6.
  • Розробник повинен переконатися, що синтаксис повинен бути != і ні оскільки деякі шрифти або інтерпретатори змінюють синтаксис != до .

Поширені запитання

The != operator returns True when two values differ, while == returns True when they are equal. Both evaluate to a Boolean True or False.

No. The <> operator worked in Python 2 but was removed in Python 3. Only != is valid in both versions, so use != in modern code.

Так. Python is dynamically typed, so != compares different types. The integer 12222 and the string “12222” are treated as not equal.

The != operator compares values and calls __ne__, checking equality. The “is not” operator compares identity, testing whether two variables reference the same object in memory.

Use “is not None”. None is a singleton, so identity checks are faster and safer than !=, which a custom __ne__ method can override.

AI assistants confirm whether != or == fits your logic, flag risky comparisons between incompatible types, and rewrite conditions to return the result you expect.

Так. ШІ traces the values and types on both sides, explains the True or False outcome, and suggests using “is not” when comparing against None.

Yes. GitHub Copilot autocompletes != conditions from a comment. Agentic AI tools refactor comparisons across a file and flag where “is not” is safer.

Підсумуйте цей пост за допомогою: