🐍 Python控制结构大冒险:让你的代码“听话”! 嘿,各位代码魔法师!今天我们要探索Python的控制结构 ——这些就像是你程序的交通警察,告诉代码该往哪走、什么时候停、什么时候绕道。准备好了吗?让我们开始这场逻辑之旅!
🎯 条件判断:代码的“选择题” 1. if-elif-else:经典三连击 temperature = 25 if temperature > 30 : print ("🔥 热死了!穿短袖短裤" ) elif temperature > 20 : print ("😊 舒适天气,穿件T恤就好" ) elif temperature > 10 : print ("🍂 有点凉,加件外套吧" ) else : print ("❄️ 好冷!羽绒服拿出来!" )
小贴士 :elif 是 else if 的缩写,Python不喜欢太长的单词!
2. 条件语句的三种形式 age = 15 if age < 18 : print ("🚫 未成年人禁止入内" ) score = 85 if score >= 60 : print ("🎉 恭喜,你及格了!" ) else : print ("😢 很遗憾,需要补考" ) weather = "rainy" if weather == "sunny" : print ("☀️ 今天是个好天气,去散步吧!" ) elif weather == "rainy" : print ("☔ 下雨了,记得带伞" ) elif weather == "snowy" : print ("❄️ 下雪了,堆个雪人吧" ) else : print ("🌤️ 天气一般,随便走走" )
3. 嵌套条件:俄罗斯套娃式判断 username = "python_master" password = "secret123" age = 20 print ("🔐 登录系统检查..." )if username == "python_master" : print ("✅ 用户名正确" ) if password == "secret123" : print ("✅ 密码正确" ) if age >= 18 : print ("🎉 登录成功!欢迎进入系统" ) else : print ("🚫 年龄不足,无法登录" ) else : print ("❌ 密码错误" ) else : print ("❌ 用户名不存在" ) if username != "python_master" : print ("❌ 用户名不存在" ) elif password != "secret123" : print ("❌ 密码错误" ) elif age < 18 : print ("🚫 年龄不足,无法登录" ) else : print ("🎉 登录成功!欢迎进入系统" )
4. 条件表达式(三元运算符):简洁的if-else score = 75 if score >= 60 : result = "及格" else : result = "不及格" print (f"成绩:{result} " )result = "及格" if score >= 60 else "不及格" print (f"成绩:{result} " )a, b = 10 , 20 max_value = a if a > b else b print (f"最大值是:{max_value} " )num = 7 parity = "偶数" if num % 2 == 0 else "奇数" print (f"{num} 是{parity} " )x = 15 category = "小" if x < 10 else ("中" if x < 20 else "大" ) print (f"{x} 属于{category} 号" )
5. 条件语句与布尔运算 age = 25 has_ticket = True is_weekend = False if age >= 18 and has_ticket: print ("🎫 可以进入电影院" ) else : print ("🚫 无法进入电影院" ) if (age >= 65 or age <= 12 ) and not is_weekend: print ("🎁 非周末时段,老人或儿童享受优惠" ) else : print ("💰 正常票价" ) is_sunny = True temperature = 28 is_holiday = True if (is_sunny and temperature > 25 ) or is_holiday: print ("🏖️ 今天适合出去玩!" )
6. 短路逻辑:Python的”聪明偷懒法” Python在判断时会偷懒,一旦知道结果就停止计算,这就是短路逻辑:
def check_name (name ): print (f"检查名字:{name} " ) return len (name) > 0 def check_age (age ): print (f"检查年龄:{age} " ) return age >= 18 print ("案例1 - and短路:" )result = check_name("" ) and check_age(20 ) print (f"结果:{result} " )print ("\n案例2 - or短路:" )result = check_name("小明" ) or check_age(16 ) print (f"结果:{result} " )x = 0 y = 5 if x != 0 and y / x > 2 : print ("计算成功" ) else : print ("安全避开除以零!" ) data = None if data and len (data) > 0 : print (f"数据长度:{len (data)} " ) else : print ("数据为空或不存在" )
7. 特殊条件判断技巧 colors = ["red" , "green" , "blue" ] color = "green" if color in colors: print (f"✅ {color} 在颜色列表中" ) text = "Python is awesome" if "awesome" in text: print ("🎯 找到了'awesome'这个词!" ) items = [] name = "" data = None if not items: print ("📦 列表是空的" ) if not name: print ("📝 姓名为空" ) if data is None : print ("❓ 数据为None" ) status_code = 404 if status_code == 200 or status_code == 201 or status_code == 202 : print ("✅ 请求成功" ) if status_code in [200 , 201 , 202 ]: print ("✅ 请求成功(简洁版)" )
8. 条件语句的最佳实践 def check_order_bad (items, balance, is_member ): if len (items) > 0 : total = sum (items) if total <= balance: if is_member: discount = 0.1 final_price = total * (1 - discount) return f"会员价:{final_price} " else : return f"原价:{total} " else : return "余额不足" else : return "购物车为空" def check_order_good (items, balance, is_member ): if len (items) == 0 : return "购物车为空" total = sum (items) if total > balance: return "余额不足" if is_member: discount = 0.1 final_price = total * (1 - discount) return f"会员价:{final_price} " return f"原价:{total} " is_logged_in = True has_permission = False is_admin_user = True if is_logged_in and (has_permission or is_admin_user): print ("🔓 允许访问敏感数据" ) age = 25 income = 50000 credit_score = 700 has_collateral = True meets_age_requirement = 18 <= age <= 65 meets_income_requirement = income >= 30000 has_good_credit = credit_score >= 650 if meets_age_requirement and meets_income_requirement and (has_good_credit or has_collateral): print ("🏦 贷款申请通过" )
🔄 循环结构:代码的“健身教练” 1. while循环:不确定次数的锻炼 thirst_level = 80 glass_count = 0 print ("💧 开始喝水..." )while thirst_level > 20 : thirst_level -= 30 glass_count += 1 print (f"喝下第{glass_count} 杯水,渴意降至{thirst_level} %" ) print (f"✅ 总共喝了{glass_count} 杯水,不渴了!" )
2. for循环:确定路线的观光 fruits = ["苹果" , "香蕉" , "橙子" , "草莓" , "西瓜" ] print ("🛒 水果摊上有:" )for fruit in fruits: print (f" - {fruit} " ) print ("\n📊 编号水果清单:" )for i in range (len (fruits)): print (f" {i+1 } . {fruits[i]} " ) print ("\n🎯 使用enumerate:" )for index, fruit in enumerate (fruits, start=1 ): print (f" 第{index} 个水果是:{fruit} " )
🚦 循环控制:代码的”紧急按钮” 1. break:火警警报(立即撤离!) coins = [1 , 1 , 5 , 1 , 10 , 1 ] total = 0 print ("💰 开始找钱..." )for coin in coins: total += coin print (f"找到{coin} 元,现在有{total} 元" ) if coin == 5 : print ("🎉 找到5元!今天收工!" ) break print (f"最终金额:{total} 元" )
2. continue:跳过这个(继续前进!) fruits = ["苹果" , "香蕉" , "橙子" , "香蕉" , "草莓" ] print ("🍽️ 开始吃水果:" )for fruit in fruits: if fruit == "香蕉" : print (" 🚫 跳过香蕉(我不喜欢)" ) continue print (f" 😋 吃掉{fruit} " ) print ("✅ 吃完了!" )
3. else子句:循环的”善后工作” numbers = [2 , 4 , 6 , 8 , 10 ] target = 5 print (f"🎯 在列表中寻找数字{target} ..." )for num in numbers: if num == target: print (f" 找到了{target} !" ) break else : print (f" 😞 没找到{target} ..." ) print ("\n🔐 验证密码复杂度:" )passwords = ["123" , "password" , "abc123" , "StrongP@ssw0rd" ] for pwd in passwords: if len (pwd) < 8 : print (f" '{pwd} ' 太短了!" ) continue if not any (char.isdigit() for char in pwd): print (f" '{pwd} ' 需要数字!" ) continue if not any (char.isalpha() for char in pwd): print (f" '{pwd} ' 需要字母!" ) continue print (f" ✅ '{pwd} ' 是强密码!" ) break else : print (" 😢 没有找到强密码..." )
🎩 进阶技巧:代码的”秘密武器” 1. 嵌套循环:俄罗斯套娃 print ("📚 九九乘法表:" )for i in range (1 , 10 ): for j in range (1 , i+1 ): print (f"{j} ×{i} ={i*j:2d} " , end=" " ) print ()
2. 列表推导式中的条件 numbers = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] evens = [x for x in numbers if x % 2 == 0 ] print (f"偶数:{evens} " )result = [x**2 if x % 2 == 0 else x**3 for x in numbers] print (f"奇偶不同处理:{result} " )
3. 海象运算符(Python 3.8+):边赋值边判断 data = "Python很有趣" length = len (data) if length > 5 : print (f"字符串长度({length} )大于5" ) if (length := len (data)) > 5 : print (f"字符串长度({length} )大于5" ) print ("\n📏 处理长单词:" )words = ["Python" , "是" , "一种" , "非常" , "有趣的" , "编程语言" ] for word in words: if (n := len (word)) > 2 : print (f" '{word} ' 有{n} 个字符" )
🏁 总结
控制结构
作用
类比
if/elif/else
条件分支
路口选择器
while
条件循环
直到满足条件
for
遍历循环
观光巴士
break
跳出循环
紧急出口
continue
跳过本次
跳过这一站
else(循环)
循环完整执行
完美收工
短路逻辑
智能判断
偷懒的聪明人
💡 条件语句黄金法则:
清晰第一 :条件表达式应该简单易懂
避免嵌套过深 :超过3层嵌套考虑重构
使用提前返回 :减少else的使用,让代码更清晰
提取复杂条件 :把复杂的判断提取到变量中
善用in运算符 :检查元素是否存在
理解短路逻辑 :利用它避免错误和提升效率
🎯 条件语句使用指南:
简单判断 :使用 if
二选一 :使用 if-else
多选一 :使用 if-elif-else
简洁赋值 :使用三元运算符
避免空值错误 :利用短路逻辑
复杂条件 :提取到变量或函数中
记住,控制结构就像厨师的刀工——基础但至关重要。掌握了它们,你就能让代码跳出优美的逻辑之舞!
import randomprint ("🎮 猜数字游戏开始!" )secret = random.randint(1 , 100 ) attempts = 0 max_attempts = 7 print ("🤔 猜一个1-100的数字,你有7次机会" )while attempts < max_attempts: try : guess = int (input (f"第{attempts+1 } 次尝试:" )) attempts += 1 if guess < 1 or guess > 100 : print ("⚠️ 请输入1-100之间的数字!" ) attempts -= 1 continue if guess < secret: print ("📈 猜小了!" ) elif guess > secret: print ("📉 猜大了!" ) else : print (f"🎉 恭喜!你用了{attempts} 次猜对了数字{secret} !" ) break remaining = max_attempts - attempts if remaining > 0 : print (f"💡 还有{remaining} 次机会" ) except ValueError: print ("❌ 请输入有效的数字!" ) else : print (f"😢 游戏结束!正确答案是{secret} " ) print ("💡 下次加油哦!" ) print ("感谢游玩!" )
祝你编程愉快,愿你的代码永远没有无限循环! 🚀🐍