1. 条件测试
cars = ['bmw', 'puma', 'msld', 'suv', 'bm']
for car in cars:
# print(car)
if car == 'bmw':
print(car.upper())
else:
print(car.title())
BMW
Puma
Msld
Suv
Bm
1.1 在Python中检查是否相等时区分大小写
1.2 检查不相等是使用 !=
1.3 比较数字 == != >= <= > <
1.4 检查多个条件 and or
1.5 检查特定值是否包含在列表中 in
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False
1.6 检查特定值不包含在列表中 not in
2. if语句:满足条件即可执行
if conditions > value :
print('YES!')
2.1 if-else语句:执行两种操作之一
if conditions > value :
print('YES!')
else:
print('NO!')
2.2 if-elif-if语句:检查超过两个,依次检查每个条件测试,直到遇到可以通过的测试
if conditions < value :
print('YES!')
elif conditions < value:
print('NO!')
else:
print('OK,Im fine!')
2.3 使用多个elif代码块
if conditions < value :
print('YES!')
elif conditions < value:
print('NO!')
elif conditions < value:
print('Oh,my god!')
else:
print('OK,Im fine!')
2.4 省略else代码块:if-elif结构后面可以不跟else模块
2.5 测试多个条件:多个if
3. 使用if处理列表
3.1 检查特殊元素
3.2 检查列表是否为空
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print('Sorry ' + requested_topping + 'is nothing')
else:
print('Addings ' + requested_topping)
print('OK.pizza is fine')
else:
print('Sorry,is nothing!')
Sorry,is nothing!
3.3 使用多个列表
available_toppings = ['mushrooms', 'green peppers', 'extra cheese']
requested_toppings = ['apple', 'bananas', 'extra cheese', 'mushrooms']
for available_toppings in available_topping:
if available_topping in requested_toppings:
print('Addings ' + available_topping)
else:
print('Sorry,is nothing!')
print('OK.pizza is fine')
Addings mushrooms
Sorry,is nothing!
Addings extra cheese
OK.pizza is fine
练习:
"""
序数表示位置,如1st和2nd。大多数序数都以th结尾,只1、2和3例外。
在一个列表中存储数字1~9。
遍历这个列表。
在循环中使用一个if-elif-else 结构,以打印每个数字对应的序数。输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每个序 数都独占一行。
"""
number_list = list(range(1, 10))
print(number_list)
for number in number_list:
if number == 1:
print('1' + 'st')
elif number == 2:
print('2' + 'nd')
elif number == 3:
print('3' + 'rd')
else:
print(str(number) + 'th')
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1st
2nd
3rd
4th
5th
6th
7th
8th
9th