cars = ["audi","bmw","subaru","toyota"]
for car in cars:
if car == "bmw":
print(car.upper())
else:
print(car.title())
可以从中看到很多if语句的格式。
if语句核心都是一个值为true或false的表达式,也就是条件测试。
(1)检查是否相等
检查是否相等使用的是双等号==,和C\C++是一样的。
(2)检查是否相等时不考虑大小写
如果不忽略大小写,那么条件检测会认为其是不相等的值,如果大小写无关紧要,可以将变量的值转变为小写然后再进行比较。
(3)检查是否不相等
检查是否不相等,可以结合使用惊叹号和等号!=表示。
(4)检查数字
检查数字和字符串是一样的操作。
(5)检查多个条件
检查多个条件有两种情况。
#使用and检查多个条件,当两个条件都为true,通过测试,下面代码条件为假,可以
#使用括号将条件测试括起来
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1>=21
#使用or检查多个条件,但只要至少一个条件为true,就可以通过测试,同样的代码
#使用or则条件测试可以通过
age_0 = 22
age_1 = 18
age_0 >= 21 or age_1>=21
(6)检查特定值是否包含在列表里
#条件测试满足
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings:
(7)检查特定值是否不包含在列表里
#条件测试不满足
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' not in requested_toppings
(8)布尔表达式
很多时候可以使用布尔表达式,其实只是条件测试的别名。布尔表达式的结果要么为True,要么为False。
#如下定义了两个布尔表达式
game_active = True
can_edit = False
# 最简单的if语句
if conditional_test:
do something
# if-else 语句
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!")
# if-elif-else,注意中间是elif,elif可以使用多个
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.")
# 同时也可以省略else语句
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
# 测试多个条件
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
#在for循环里添加if语句,判断特殊元素
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!")
#确定列表不是空的,python中列表名如果是条件表达式,则其为空返回False,不为
#空返回True
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?")
# 使用多个列表,python可以非常便利的遍历一个列表里的元素是否存在于另一个列表
# 如下代码,当遍历到第二个列表的french fries元素时,条件判断返回False
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 + ".")
建议在==,>=,<=等比较运算符两边都添加一个空格。