一、算术运算符

1.1 基本算术运算符

# 加减乘除
a = 10
b = 3

print(a + b)   # 加法:13
print(a - b)   # 减法:7
print(a * b)   # 乘法:30
print(a / b)   # 除法:3.333...(浮点数结果)

# 特殊算术运算符
print(a // b)  # 整除:3(向下取整)
print(a % b)   # 取模:1(求余数)
print(a ** b)  # 幂运算:1000(10的3次方)

1.2 算术运算符的优先级

# 优先级:** > * / // % > + -
result1 = 2 + 3 * 4      # 14(先乘后加)
result2 = (2 + 3) * 4    # 20(括号改变优先级)
result3 = 2 ** 3 * 4     # 32(先幂运算后乘法)

二、比较运算符

2.1 基本比较运算符

x = 10
y = 5

print(x > y)    # 大于:True
print(x < y)    # 小于:False
print(x >= y)   # 大于等于:True
print(x <= y)   # 小于等于:False
print(x == y)   # 等于:False
print(x != y)   # 不等于:True

2.2 字符串比较

# 字符串按字典序比较
print("apple" < "banana")    # True
print("abc" == "abc")        # True
print("ABC" < "abc")         # True(大写字母ASCII码小于小写字母)

三、逻辑运算符

3.1 基本逻辑运算符

# and(与):两个条件都为True时返回True
print(True and True)     # True
print(True and False)    # False

# or(或):至少一个条件为True时返回True
print(True or False)     # True
print(False or False)    # False

# not(非):取反
print(not True)          # False
print(not False)         # True

3.2 实际应用示例

age = 25
has_license = True
is_employed = False

# 复合条件判断
can_drive = age >= 18 and has_license  # True
is_eligible = age > 20 or is_employed  # True
cannot_drive = not (age >= 18 and has_license)  # False

四、赋值运算符

4.1 复合赋值运算符

# 基本赋值
x = 10

# 复合赋值
x += 5      # 等同于 x = x + 5,现在x=15
x -= 3      # 等同于 x = x - 3,现在x=12
x *= 2      # 等同于 x = x * 2,现在x=24
x /= 4      # 等同于 x = x / 4,现在x=6.0
x //= 2     # 等同于 x = x // 2,现在x=3.0
x %= 2      # 等同于 x = x % 2,现在x=1.0
x **= 3     # 等同于 x = x ** 3,现在x=1.0

五、示例

成绩计算器

# 计算加权平均分
math_score = 85
english_score = 92
programming_score = 88

math_weight = 0.4
english_weight = 0.3
programming_weight = 0.3

weighted_average = (math_score * math_weight + 
                   english_score * english_weight + 
                   programming_score * programming_weight)

print(f"加权平均分: {weighted_average:.2f}")

本文为原创内容,转载请注明出处。
来源:飞记资源网,作者:小兔

标签: python

添加新评论