Python学习笔记(4)-if语句
来源:互联网 发布:java中else是什么意思 编辑:程序博客网 时间:2024/04/28 19:05
(和java大同小异,写法上稍有不同,可对比着记忆)
条件测试
相等和不等
代码:
car = 'bmw' #赋值语句print(car == 'bmw') #判断语句,判断是否相等,相等返回True,不等返回False
结果:
True
(PS: 需要注意相比字符串的大小写,python对大小写敏感)
不等的判断为!=
代码:
car = 'bmw'print(car != 'bssw')
结果:
True
数字除了是否相等外还有有大小的比较
符号有=
,>
,>=
,<
,<=
代码:
age = 18print(age == 18)print(age > 18)print(age >= 18)print(age < 18)print(age <= 18)
结果:
TrueFalseTrueFalseTrue
检查多个条件
- 使用
and
检查(左右两个条件都成立返回True,否则返回False) - 使用
or
检查(左右两个条件只要有一个成立返回True,否则返回False)
代码:
my_age = 18your_age = 60print(my_age <= 30 and your_age <= 30)print(my_age <= 30 or your_age <= 30)
结果:
FalseTrue
检查特定值是否包含在列表中
- in
- not in
代码:
pets = ['dog', 'cat', 'fox']print('dog' in pets)print('dog' not in pets)
结果:
TrueFalse
布尔表达式
boolean值只能为True
或者 False
,赋值即可
can_read = True
if语句
- 简单的if语句
- if-else语句
- if-elif-else语句
代码:
age = 18if age >= 18: print("Adult")age = 17if age >= 18: print("Adult")else: print("Young")age = 2if age >= 18: print("Adult")elif age <= 5: #注意是elif,和java不同 print("Baby")else: print("Young")
结果:
AdultYoungBaby
if语句处理列表
代码:
foods = ['bread', 'meat', 'milk', 'tomato']for food in foods: if food == 'meat': #判断语句 print(food + " is not enough") else: print(food + "is added")
结果:
breadis addedmeat is not enoughmilkis addedtomatois added
确定列表不是空的
foods = []if foods: #在列表有值的时候返回True,空的时候返回False print("There's something.")else: print("blank")
结果:
blank
提示:if sth:
中,只要sth
不是数字0,其他非零数字,非空列表,非空字典,非空字符串等都符合该条件
使用多个列表
代码:
now_foods = ['meat', 'mile', 'tomato', 'bread'] #现有的食物request_foods = ['watermelon', 'mile', 'pear', 'bread'] #需要的食物for request_food in request_foods: if request_food in now_foods: #每个需要的食物都到现有的食物中去判断是否存在 print(request_food + " is added.") else: print(request_food + " is not enough.")
结果:
watermelon is not enough.mile is added.pear is not enough.bread is added.
0 0
- Python学习笔记(4)-if语句
- Python学习笔记(8)- if语句
- python 学习笔记 if语句
- Python学习笔记(九):if、while、for语句
- Python学习笔记(二)if语句的简单用法
- Python学习笔记(二):if语句的使用
- Python学习笔记四:if语句
- Python学习笔记03-if语句
- 【学习笔记】Python条件判断-If语句
- Python学习:if语句
- Python编程入门学习笔记——if语句
- if语句(python)
- [python学习手册]if语句
- 学习Python语言---If语句
- Python学习(7)--if语句
- Python学习笔记之IF
- Java学习笔记(条件运算/运算符优先级/条件语句if/if..else/多重if/嵌套if)
- python学习之路四--if语句
- ecshop php 建设银行 支付接口
- DCT变换
- String - 习题练习
- MyBaits association的使用、 association详解
- C++文件型日志类 v0.2
- Python学习笔记(4)-if语句
- 正则表达式(二)
- 超分辨率重建——病态、单应矩阵、高斯权重
- Android 7.0 新技术
- 最小生成树(prim算法)
- Java / JSP的I / O操作实例
- Java基础知识
- ecshop php 中国银行 支付 接口
- Drawable子类——ScaleDrawable