cars = ['audi','bmw','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
每条if 语句的核心都是一个值为True 或False 的表达式,这种表达式被称为条件测试 。
1、检查是否相等
将变量当前值与特定值进行比较。
2、检查是否相等时不考虑大小写
当大小写不是很重要,可将变量的值转换为小写后比较。
3、检查是否不相等
判断两个值是否不相等,可结合使用感叹号和等号(!=);!表示 不 。
4、比较数字
age = 18
if age == 18:
print(age == 18)
5、检查多个条件
and or
6、检查特定值是否包含在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings:
print('mushrooms' in requested_toppings)
7、检查特定值是否不包含在列表中
not in
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ",you can post a response if you wish.")
8、布尔表达式
条件测试的别名
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
1、检查特殊元素
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
2、确定列表不是空
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
3、使用多个列表
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如== 、>= 和<= 等比较运算符两边各添加一个空格,例如,if
age < 4: 要比if age<4: 好。 这样的空格不会影响Python对代码的解读,而只是让代码阅读起来更容易。