# Python中的运算符示例
# 1. 算术运算符
a = 10
b = 3
# 加法
print(f"{a} + {b} = {a + b}") # 输出: 10 + 3 = 13
# 减法
print(f"{a} - {b} = {a - b}") # 输出: 10 - 3 = 7
# 乘法
print(f"{a} * {b} = {a * b}") # 输出: 10 * 3 = 30
# 除法
print(f"{a} / {b} = {a / b}") # 输出: 10 / 3 = 3.3333333333333335
# 取整除
print(f"{a} // {b} = {a // b}") # 输出: 10 // 3 = 3
# 取余
print(f"{a} % {b} = {a % b}") # 输出: 10 % 3 = 1
# 幂运算
print(f"{a} ** {b} = {a ** b}") # 输出: 10 ** 3 = 1000
# 2. 比较运算符
x = 5
y = 8
# 等于
print(f"{x} == {y}: {x == y}") # 输出: 5 == 8: False
# 不等于
print(f"{x} != {y}: {x != y}") # 输出: 5 != 8: True
# 大于
print(f"{x} > {y}: {x > y}") # 输出: 5 > 8: False
# 小于
print(f"{x} < {y}: {x < y}") # 输出: 5 < 8: True
# 大于等于
print(f"{x} >= {y}: {x >= y}") # 输出: 5 >= 8: False
# 小于等于
print(f"{x} <= {y}: {x <= y}") # 输出: 5 <= 8: True
# 3. 赋值运算符
m = 7
n = 2
# 简单赋值
m = n
print(f"m = n: m is now {m}") # 输出: m = n: m is now 2
# 加法赋值
m += n
print(f"m += n: m is now {m}") # 输出: m += n: m is now 4
# 减法赋值
m -= n
print(f"m -= n: m is now {m}") # 输出: m -= n: m is now 2
# 乘法赋值
m *= n
print(f"m *= n: m is now {m}") # 输出: m *= n: m is now 4
# 除法赋值
m /= n
print(f"m /= n: m is now {m}") # 输出: m /= n: m is now 2.0
# 4. 逻辑运算符
p = True
q = False
# 与
print(f"p and q: {p and q}") # 输出: p and q: False
# 或
print(f"p or q: {p or q}") # 输出: p or q: True
# 非
print(f"not p: {not p}") # 输出: not p: False
# 5. 位运算符
c = 6 # 二进制: 110
d = 2 # 二进制: 010
# 按位与
print(f"c & d: {c & d}") # 输出: c & d: 2
# 按位或
print(f"c | d: {c | d}") # 输出: c | d: 6
# 按位异或
print(f"c ^ d: {c ^ d}") # 输出: c ^ d: 4
# 左移
print(f"c << 1: {c << 1}") # 输出: c << 1: 12
# 右移
print(f"c >> 1: {c >> 1}") # 输出: c >> 1: 3
# 6. 成员运算符
list_example = [1, 2, 3, 4, 5]
# in
print(f"3 in list_example: {3 in list_example}") # 输出: 3 in list_example: True
# not in
print(f"6 not in list_example: {6 not in list_example}") # 输出: 6 not in list_example: True
# 7. 身份运算符
str1 = "hello"
str2 = "hello"
# is
print(f"str1 is str2: {str1 is str2}") # 输出: str1 is str2: True (因为字符串是不可变对象,Python会重用它们)
# is not
print(f"str1 is not str2: {str1 is not str2}") # 输出: str1 is not str2: False
下一篇:python 打印时间
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站