Python编程:从入门到实践-if 语句
-
简单示例
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 cars = ['audi', 'bmw', 'subaru', 'toyota'] 4 for car in cars: 5 if car == 'bmw': 6 print(car.upper()) 7 else: 8 print(car.title())

C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/demo.py
Audi
BMW
Subaru
Toyota
-
条件测试
-
检查是否相等
1 2 3 4 5 6 7 | >>> car = 'bmw' >>> car = = 'bmw' True >>> car = 'audi' >>> car = = 'bmw' False >>> |
-
检查是否相等时不考虑大小写
1 2 3 4 5 6 | >>> car = 'Audi' >>> car = = 'audi' False >>> car = 'Audi' >>> car.lower() = = 'audi' True |
-
检查是否不相等
1 requested_toppings = 'mushrooms' 2 if requested_toppings != 'anchovies': 3 print("Hold the anchovies!")
-
比较数字
1 2 3 | >>> age = 18 >>> age = = 18 True |
1 2 3 4 5 | #!/usr/bin/env python #-*- encoding:utf-8 -*- answer = 17 if answer ! = 42 : print ( "That is not the correct answer.Please try again!" ) |
1 2 | C:\PyProjects>C: / Python37 / python3.exe c: / PyProjects / demo.py That is not the correct answer.Please try again! |
-
检查多个条件
使用and检查多个条件
1 2 3 4 5 6 7 | >>> age_0 = 22 >>> age_1 = 18 >>> age_0 > = 21 and age_1 > = 21 False >>> age_1 = 22 >>> age_0 > = 21 and age_1 > = 21 True |
使用or检查多个条件
1 2 3 4 5 6 7 | >>> age_0 = 22 >>> age_1 = 18 >>> age_0 > = 21 or age_1 > = 21 True >>> age_0 = 18 >>> age_0 > = 21 or age_1 > = 21 False |
-
检查特定值是否包含在列表
1 2 3 4 5 6 | >>> requested_toppings = [ 'mushrooms' , 'onions' , 'pineapple' ] >>> 'mushrooms' in requested_toppings True >>> 'pepperoni' in requested_toppings False >>> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南