1. 示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
2. 条件测试
布尔值:True和False
# 检查相等或不等
== # 变量相等
!= # 变量不等
< <= == >= > # 数值比较
# 多个条件
and
or
# 检查特定值是否在列表中
'audi' in cars
# 检查特定值是否不在列表中
if 'audi' not in cars:
print('not in')
3. if语句
3.1 简单if语句
age = 19
if age >= 18:
print('you area old enough to vote!')
3.2 if-else语句
age = 13
if age >= 18:
print('you area old enough to vote!')
else:
print('sorry! you area too young to vote.')
3.3 if-elif-else语句
age = 12
if age < 4:
print('Your admission cost is $0.')
elif age < 18:
print('Your admission cost is $25.')
else:
print('Your admission cost is $40.')
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f'Your admission cost is ${price}.')