1. 条件测试
fa_fruit = 'Apple'
print(fa_fruit == 'apple') # False
print(fa_fruit.lower() == 'apple') # True
print(fa_fruit) # Apple
1.1. 检查是否不相等
my_fruit = 'apple'
if my_fruit != 'pear':
print("It's not pear!") # It's not pear!
else:
print("It's pear!")
1.2. 比较数字
age = 25
print(age == 25) # True
print(age < 18) # False
print(age <= 25) # True
print(age > 30) # False
print(age >= 15) # True
if age != 20:
print("This is not the correct answer!")
# This is not the correct answer!
1.3. and和or
num_1 = 18
num_2 = 20
print((num_1 >= 20) and (num_2 >= 20)) # False
num_1 = 21
print((num_1 >= 20) and (num_2 >= 20)) # True
print((num_1 >= 20) or (num_2 >= 25)) # True
print((num_1 >= 22) or (num_2 >= 22)) # False
2. 检查特定值是否包含在列表中
2.1. in与 not in用法
grades = ['A', 'B', 'C']
print('A' in grades) # True
print('D' in grades) # False
score = 'E'
if score not in grades:
print("This is out of scope")
# This is out of scope
3. if语句
age = 24
if age >= 18:
print('你已满18岁!')
print('你成年了!')
# 你已满18岁!
# 你成年了!
3.1. if-else语句
money = 20
if money >= 30:
print('你可以买一本书')
print('可以买30元及以上的书')
else:
print('你不能买30元及以上的书')
print('你可以买30元以内的书')
# 你不能买30元及以上的书
# 你可以买30元以内的书
3.1.1 if-elif-else结构
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
print("You got " + grade + '.') # You got B.
3.1.2 使用多个elif代码块
可以不使用else
score = 70
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score < 80:
grade = 'C'
print("You got " + grade + '.') # You got C.
3.1.3 测试多个条件
colors = ['blue', 'red']
if 'blue' in colors:
print('you like blue!')
if 'red' in colors:
print('you like red!')
# you like blue!
# you like red!
3.2. 习题
age = 24
if age < 2:
print("婴儿")
elif age < 4:
print("蹒跚学步")
elif age < 13:
print("儿童")
elif age < 20:
print("青少年")
elif age < 65:
print("成年人")
elif age >= 65:
print("老年人")
# 成年人
4. 使用if语句处理列表
4.1. 检查特殊元素
fruits = ['apple', 'pear', 'banana']
for fruit in fruits:
if fruit == 'pear':
print("lack pear.")
else:
print("enough " + fruit + '.')
# enough apple.
# lack pear.
# enough banana.
4.1.1 检查列表是否为空
lists = []
if lists:
for list in lists:
print(list)
else:
print("empty!")
# empty!
4.1.2 使用多个列表
enough_fruits = ['apple', 'banana', 'orange']
love_fruits = ['apple', 'peach']
for love_fruit in love_fruits:
if love_fruit in enough_fruits:
print("I‘ll give you " + love_fruit + '!')
else:
print('Sorry,' + love_fruit + ' is not enough!')
# I‘ll give you apple!
# Sorry,peach is not enough!