x = [1, 2]
y = [1, 2]
print(x == y) # equality operator
print(x is y) # identity operator
# Output:
True
False
a = 2
b = 2
print(a == b) # equality operator
print(a is b) # identity operator
# Output:
True
True
o = 'b' > 'a'
print(o)
# Output:
True
o = [1, 2] > [2, 1]
print(f"1. {o}")
o = [4, 1] > [3, 1]
print(f"2. {o}")
o = [1, [2, 3]] > [1, [2, 4]]
print(f"3. {o}")
o = [1, [2, 10]] > [1, [2, 9]]
print(f"4. {o}")
# Output:
1. False
2. True
3. False
4. True
# Implied truth values
test_values = [0, 0.00, None, "", [], 1]
for tv in test_values:
if tv == '':
print(f"truth value of '': {bool(tv)}")
else:
print(f"truth value of {str(tv)}: {bool(tv)}")
# 결과
truth value of 0: False
truth value of 0.0: False
truth value of None: False
truth value of '': False
truth value of []: False
truth value of 1: True
# Python Truth Value Testing
# ==========================
# X and Y: True if X and Y are both True
# X or Y: True if either X or Y are True
# not X: if x is false, then True, else False
class myClass:
def __bool__(self):
return False
def __len__(self):
return 0
mc = myClass()
print(bool(mc))
# Output:
False
# walrus operator (aka. Assignment Expressions)
# ===============
# 표현식의 결과를 변수에 할당한 후 동시에 다시 반환함
# The walrus operator can help reduce redundant function calls
values = [12, 0, 10, 5, 9]
val_data = {
"length": (l := len(values)),
"total": (s := sum(values)),
"average": s/l
}
print(val_data)
# Output:
{'length': 5, 'total': 36, 'average': 7.2}
댓글 영역