注:本篇完成时使用的Python版本为3.13.0
Python中,判断两变量是否相同,通常有is(is not)和 ==(!=)两种方法。
1、is / is not 身份运算符
用于比较两个对象的存储单元,即判断两个对象标识符是否引用自同一对象。
示例1:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
d = a.copy()
e = a[:]
print(f"a and b: {b is a}")
print(f"a and c: {c is a}")
print(f"a and d: {d is a}")
print(f"a and e: {e is a}")
结果为:
a and b: True
a and c: False
a and d: False
a and e: False
示例2:
a = 10
b = a
c = 10
d = 10.0
print(f"a and b: {b is a}")
print(f"a and c: {c is a}")
print(f"a and d: {d is a}")
e = 2 ** 60
f = 2 ** 60
print(f"e and f: {f is e}")
g = 2 ** 80
h = 2 ** 80
print(f"g and h: {h is g}")
i = -100
j = -100
print(f"i and j: {j is i}")
k = 10.0
print(f"d and k: {k is d}")
l = "hello"
m = "hello"
print(f"l and m: {m is l}")
结果为:
a and b: True
a and c: True
a and d: False
e and f: True
g and h: False
i and j: Trued and k: True
l and m: True
可以发现,python3.13中,会预先创建部分int型、float型变量和简单字符串,当程序中使用的变量值在上述范围内时,均为对预创建变量的引用。
2、== / != 比较运算符
用于比较两对象的值,判断其是否相等。
示例1:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
d = a.copy()
e = a[:]
f = a[:2]
g = a[1:]
print(f"a and b: {b == a}")
print(f"a and c: {c == a}")
print(f"a and d: {d == a}")
print(f"a and e: {e == a}")
print(f"a and f: {f == a}")
print(f"a and g: {g == a}")
结果为:
a and b: True
a and c: True
a and d: True
a and e: True
a and f: False
a and g: False
示例2:
a = 10
b = a
c = 10
d = 10.0
print(f"a and b: {b == a}")
print(f"a and c: {c == a}")
print(f"a and d: {d == a}")
结果为:
标签:10,相等,False,示例,Python,判断,10.0,print,True From: https://blog.csdn.net/2401_86792055/article/details/144581073a and b: True
a and c: True
a and d: True