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.

什么是 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.
不等于运算符的类型及其语法 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
如何使用“不等于” Opera使用 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 循环也可以与不等于运算符一起使用。让我们以使用 while 循环和不等于运算符打印偶数为例,如下所示:–
m = 300
while m <= 305:
m = m + 1
if m%2 != 0:
continue
print (m)
输出:
302 304 306
这里,不等于 != 与 if 语句一起使用。
使用方法 Python 不平等 Opera自定义对象
自定义对象使用户或开发人员能够创建自定义实现。这使开发人员能够更改通常预期以外的实际输出。
让我们举一个使用不等于运算符的自定义对象的示例,如下所示:-
计费示例:
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器 | 意 | 例如: |
|---|---|---|
!= |
不等于 - 如果操作数不具有相同的值,则返回 true | A!=B |
== |
等于 - 如果操作数具有相同的值,则返回 true | 答案==B |
>= |
大于或等于 - 如果第一个操作数大于或等于第二个操作数,则返回 true | A>=B |
<= |
Less 大于或等于 - 如果第一个操作数是 Less 大于或等于第二个操作数 | A<=B |
> |
大于 – 如果第一个操作数大于第二个操作数,则返回 true | 甲>乙 |
< |
Less than – 如果第一个操作数是 Less 比第二个操作数 | A<B |
关于“不等于”的实用技巧 Opera器
以下是一些有用的提示
- 不等于运算符可用于格式化的字符串。
- 此功能相对较新,并且是 Python 版本 3.6.
- 开发人员应确保语法
!=并不是≠因为有些字体或解释器会改变语法!=至≠.
