python if语句 5
1.条件测试
cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car=='bmw': print(car.upper()) else: print(car.title()) #下面检查不相等 != top='mus' if top!='ac': print(top) #使用and 检查多个条件 age,score=20,80 if age>18 and score>70: print(f"{age},{score}") #使用or 检查多个条件 if age>18 or score>90: print(f"{age},{score}") # 检查列表中是否包含 banned=['andrew','carolina','david'] user='marie' if user in banned: print(f"存在{user}") if user not in banned: print(f"不存在{user}") #布尔表达式 game_active=True can_edit=False if game_active: print ("激活游戏")
2. if 语句
# if elif else age=12 if age<4: print('your admission cost is $0') elif age<18: print('your admission cost is $25') elif age<20: print('your admission cost is $30') else: print('your admission cost is $40') #测试多个条件 requested_toppings=['mushrooms','extra cheese'] if 'mushrooms' in requested_toppings: print("adding mushrooms") if 'extra cheese' in requested_toppings: print("adding extra cheese") if 'm' in requested_toppings: print ("adding m")
3.使用if语句处理列表
#确定列表不是空的 requested_toppings=[] if requested_toppings: for requested_topping in requested_toppings: print(requested_topping) else: print ("list is empty") #使用多个列表, 获取requestes元素存在于avaliables中的 avaliables=['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requestes= ['mushrooms', 'french fries', 'extra cheese'] for avaliable in avaliables: if avaliable in requestes: print(f"adding {avaliable}") else: print(f"we don't have {avaliable}")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下