python-tutorial/0004/operator.py
2025-08-22 17:26:06 +08:00

67 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 算术运算符
print(5 + 3) # 加法
print(5 - 3) # 减法
print(5 * 3) # 乘法
print(5 / 3) # 除法,结果为浮点数
print(5 // 3) # 整除,结果为整数
print(5 % 3) # 取模(余数)
print(5 ** 3) # 幂运算
# 比较运算符
print(5 == 3) # 等于
print(5 != 3) # 不等于
print(5 > 3) # 大于
print(5 < 3) # 小于
print(5 >= 3) # 大于等于
print(5 <= 3) # 小于等于
# 赋值运算符
x = 5
x += 3 # x = x + 3
print(x)
x -= 3 # x = x - 3
print(x)
x *= 3 # x = x * 3
print(x)
x /= 3 # x = x / 3
print(x)
x //= 3 # x = x // 3
print(x)
x %= 3 # x = x % 3
print(x)
x **= 3 # x = x ** 3
print(x)
# 逻辑运算符
a = True
b = False
print(a and b) # 逻辑与
print(a or b) # 逻辑或
print(not a) # 逻辑非
"""
基础:计算表达式 7 + 3 * (10 / 2) 的结果。
"""
result = 7 + 3 * (10 / 2)
print(result)
"""
应用:编写一个条件语句,判断一个数是正数、负数还是零。
"""
num = 10
if num > 0:
print(f"{num}是正数")
elif num == 0:
print(f"{num}是零")
else:
print(f"{num}是负数")
"""
挑战使用逻辑运算符编写一个表达式来判断一个年份是否是闰年能被4整除且不能被100整除或者能被400整除
"""
year = 2008
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year}是闰年")
else:
print(f"{year}是平年")