文章目录
一、条件测试
1.定义
条件测试即判断表达式值为True还是False。
若值为True,则执行紧跟在if语句后面的代码;否则,不执行。
2.相关操作
(1)检查是否相等
若要判断两个值是否相等,使用相等运算符(==)
注: 相等运算符要与赋值运算符(=)区分开来
eg:
cities = ['beijing','shanghai','guangzhou']
for city in cities:
if city == 'shanghai':
print(city.title())
输出结果为:
(2)检查是否不等
若要判断两个值是否不相等,使用不等运算符(!=)
eg:
cities = ['beijing','shanghai','guangzhou']
for city in cities:
if city != 'shanghai':
print(city.upper())
输出结果为:
(3)检查特定值是否在列表中
若要判定特定的值是否在列表中,可使用关键字in
(4)检查特定值是否不在列表中
若要判定特定的值是否不在列表中,可使用关键字not in
(5)检查多个条件
1)使用and检查
条件必须均满足才返回True;否则返回False
2)使用or检查
条件至少有一个满足则返回True;否则返回False
二、条件语句
1.if语句
若只需要判断一种情况,则使用if语句
eg:
grade = 65
if grade >= 60:
print("You pass the exam.")
输出结果为:
2.if-else语句
若需要判断两种情况,则使用if-else语句
eg:
grade = 55
if grade >= 60:
print("You pass the exam.")
else:
print("You are not pass the exam.")
输出结果为:
3.if-elif-else语句
若需要判断三种情况,则使用if-elif-else语句
eg:
age = 15
if age < 4:
print("Your cost is $0.")
elif age<18:
print("Your cost is $10.")
else:
print("Your cost is $20.")
输出结果为:
4.if-多个elif-else语句
若需要判断多种情况,则使用if-多个elif-else语句
eg:
age = 85
if age < 4:
print("Your cost is $0.")
elif age<18:
print("Your cost is $10.")
elif age<65:
print("Your cost is $20.")
else:
print("Your cost is $0.")
输出结果为:
总结
以上就是今天要讲的内容,本文简要介绍了条件测试以及条件语句。