year =2024
is_leap =(year %4==0and year %100!=0)or(year %400==0)print(f"{year}年是{'闰'if is_leap else'平'}年")
4.2 日期星期计算
# 蔡勒公式应用
y, m, d =2023,8,15if m <3:
m +=12
y -=1
h =(d +13*(m+1)//5+ y + y//4- y//100+ y//400)%7
weekdays =["六","日","一","二","三","四","五"]print(f"该日期是星期{weekdays[h]}")
5. 编程训练题
5.1 成绩奖励系统
'''
奖励规则:
1. 任意单科满分
2. 两科90+
3. 三科80+
满足任一条件即可获奖
'''
chinese =95
math =92
english =88
condition1 =(chinese==100)or(math==100)or(english==100)
condition2 =(chinese>90and math>90)or(chinese>90and english>90)or(math>90and english>90)
condition3 =(chinese>80)and(math>80)and(english>80)if condition1 or condition2 or condition3:print("获得小红花!")
5.2 购物方案优化
'''
预算X元购买6/5/4元三种商品:
- 优先购买最多数量
- 必须刚好用完预算
'''
x =27
a = b = c =0
mod = x %4if mod ==0:
c = x//4elif mod ==1:
c = x//4-1
b =1elif mod ==2:
c = x//4-1
a =1else:
c = x//4-2
a, b =1,1print(f"6元商品:{a}个,5元商品:{b}个,4元商品:{c}个")
6. 常见问题解答
Q:如何避免条件判断错误?
使用括号明确运算顺序
优先处理边界条件
添加调试打印语句验证中间结果
Q:多条件判断如何优化?
# 使用集合运算优化
scores =[85,92,78]ifsum(1for s in scores if s ==100)>=1:print("有满分科目")ifsum(1for s in scores if s >90)>=2:print("两科90+")