Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python中的运算符

作者:倾尽尘光暖流年   发布日期:2026-02-10   浏览:91

# 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

上一篇:pandas在python中的用法

下一篇:python 打印时间

大家都在看

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站