一、条件测试
1、检查相等、不等、数值比较
if语句能让你检查程序的当前状态。每条if语句的核心都是一个值为True或False的表达式,这种表达式称为条件测试。
大多数条件测试都是将一个变量的当前值同特定值进行比较,最简单的条件测试是检查变量的值与特定值是否相等(==)。检查不等(!=),检查数值也非常简单。一个简单的例子:
cars=['audi','bmw','subaru','toyota'] for car in cars: if car=='bmw': print(car.upper()) else: print(car.title())
2、检查多个条件
使用and检查多个条件,如果每个测试为True,整个表达式就为真,如果至少一个测试没有通过,则整个表达式为False。
关键字or也能检查多个条件,只要至少一个条件满足,就能通过整个测试,仅当两个测试都没通过,表达式为False。
3、检查列表中的特定值
检查特定值是否包含在列表中,可用关键字in,检查特定值是否不包含在列表中用not in,
banned_users=['andrew','carolina','david'] user='andrew' if user in banned_users: print(banned_users[1:3]) user='marie' if user not in banned_users: print(user.title()+",you can post a response if you wish.")
4、布尔表达式
布尔表达式只是条件测试的别名,与条件测试一样,布尔表达式结果要么为True,要么为False。常用与记录条件。
二、if语句
简单的if语句,if-else语句。
age=19 if age>=18: print("You are old enough to vote!") print("Have you registered to vote yet?")
1、if-elif-else语句
python只执行if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到合格的条件测试,测试通过后,python将执行紧跟在他后面的代码块,并跳过余下的测试。
age=13 if age<4: price=0 elif age<18: price=5 else: price=10 print("Your admission is $"+str(price)+".")
2、使用多个elif代码块
age=67 if age<4: price=0 elif age<18: price=5 elif age<65: price=10 else: price=5 print("Your admission is $"+str(price)+".")
有时候else语句是可以省略的,用elif语句更清晰,如上面例子中将最后一个条件改为elif age>=65:price=5。如果你只想执行一个代码块,就使用if-elif-else结构,如果要执行多个代码块,就是用一系列独立的if语句。
三、使用if语句处理列表
1、检查特殊元素
在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!")
2、确定列表不是空的
不想上面例子那样,我们先做一个简单的检查,用if语句将列表名用在条件表达式中。
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','gerrn peppers', 'pepperoni','pineapple','extra cheese'] requested_toppings=['mushrooms','french fries','extra cheese'] for requested_topping in requested_toppings: if requested_topping in requested_toppings: print("Adding "+requested_topping+".") else: print("Sorry,we don't have "+requested_topping+'.') print("\nFinished making your pizza!")
PEP 8建议在if语句中,诸如==,>=,<=,!=等比较运算符两边各添加一个空格。