Python 判断、循环与函数联动实战教程
★ (Tutorial on Integrating Conditionals, Loops, and Functions)
示例代码短小精悍,让你快速上手!
示例 1:天气出行建议 ??
根据当天天气给出出行提示,利用函数、条件表达式和循环。
def weather_advice(weather):
return "带伞" if weather=="雨" else "出门享受阳光" # (Bring an umbrella if raining, else enjoy the sun)
for day in ["雨", "晴", "多云"]:
print(day, "->", weather_advice(day))
解释: 使用三元表达式判断天气,并用循环打印每一天的建议。
示例 2:咖啡订单优惠计算 ??
计算咖啡订单总价,订单金额超过50元享受9折优惠。
def calc_order(coffee, pastry):
total = coffee * 15 + pastry * 10
return total * 0.9 if total > 50 else total
orders = [(2, 1), (3, 2), (1, 0)]
for o in orders:
print("订单", o, "总价:", calc_order(*o))
解释: 使用条件判断实现折扣优惠,循环遍历多个订单进行计算。
示例 3:健身计划生成 ?
根据目标和天数生成简易健身建议,示例中仅生成前三天计划。
def workout(day, goal):
if goal=="增肌":
return "重量训练" if day % 2 == 0 else "力量训练"
elif goal=="减脂":
return "有氧运动"
return "休息"
for d in range(3):
print("Day", d+1, "->", workout(d, "增肌"))
解释: 利用条件判断区分不同训练类型,并用循环生成每日计划。
示例 4:温度转换助手 ?
将华氏温度转换为摄氏温度,用于日常温度参考。
def to_celsius(f):
return (f - 32) / 1.8
for f in [68, 77, 86]:
print(f"{f}℉ -> {to_celsius(f):.1f}℃")
解释: 简单函数计算温度转换,循环遍历多个温度值并格式化输出。
示例 5:简单菜单选择
模拟一个菜单选项,根据用户选择给出不同反馈。
def menu(choice):
if choice == 1:
return "开始游戏"
elif choice == 2:
return "加载游戏"
else:
return "退出游戏"
for c in [1, 2, 3]:
print("选项", c, "->", menu(c))
解释: 用条件判断实现菜单功能,并用循环展示各个选项的反馈。
Implement the menu function using conditional statements, and utilize loops to display the feedback for each option.
★ 总结
快试试这些短小精悍的代码,感受 Python 的魅力吧!如果觉得有帮助,请点赞、收藏并关注我,共同进步! Happy coding! ?