目录
- 一、条件测试
- 1.1 检测多个条件(and / or)
- 1.2 检测特定值是否包含在列表中
- 1.3 if语句结构
- 二、if语句处理列表
- 2.1 判断列表是否为空
- 2.2 练习题
- 代码
- 输出
一、条件测试
1.1 检测多个条件(and / or)
所用关键词
- and : 两个条件都为true
- or :至少满足一个条件
实例
age_o=20
age_1=22
print(age_o>=21 and age_1<=22,age_o>=21 or age_1<=22)
1.2 检测特定值是否包含在列表中
所用关键词
- 判断特定值在列别中:in
- 判断特定值不在列表中:not in
实例
color = ['green','red','blue','yellow','pink']
if 'pink' in color:
print('yes!')
if 'dark' not in color:
print('sorry!')
1.3 if语句结构
- 单if语句
- if-else语句
- if-elif-else语句
二、if语句处理列表
2.1 判断列表是否为空
三种方法判断:
- 直接使用条件表达式if + list,如果list不为空,if list表达式返回true,否则返回false
- 检测列表是否==【】
- 按列别长度进行判断
list_1 = []
if list_1:
print('This is not a empty list!')
else:
print('This is a empty list!')
if list_1==[]:
print('This is a empty list!')
else:
print('This is not a empty list!')
if len(list_1)==0:
print('This is a empty list!')
else:
print('This is not a empty list!'
2.2 练习题
代码
print('5-8')
usernames = ['root','admin','jack','peter','diane']
for username in usernames:
if username == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello Jaden, thank you for logging in again.')
print('5-9')
usernames.clear()
if usernames:
for username in usernames:
if username == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello Jaden, thank you for logging in again.')
else:
print('We need to find some users!')
print('5-10')
current_users = ['jack','peter','will','admin','diane']
new_users = ['mary','peter','will','lili','frank']
for new_user in new_users:
for current_user in current_users:
if new_user == current_user:
print(f'Dear {new_user.title()}, you need to change a username!')
break;
else:
print(f'Dear {new_user.title()}, this username is ready to use!')
else:
print('All the usernames are finished checked!')
print('5-11')
numbers = list(range(1,10))
for number in numbers:
if number==1:
print('first')
elif number == 2:
print('second')
elif number==3:
print('third')
else:
print(f'{number}th')
输出
注:清空列表的方法
- 使用clear方法
- 直接让列表==[]
- 使用del语句:del [:],不指定起始和结束索引,把所有元素全部删除
清空列表