使用if来进行判断:
cars=['audi','bmw','subaru','toyota'] for car in cars: if car=='bmw': print(car.upper()) else: print(car.title())
if代表条件测试,根据条件测试的值是True还是False来决定是否运行if语句中的代码
①检查是否相等
==表示判断是否相等
=表示赋值
在Python中检查是否相等是区分大小写的,两个大小写不同的值被视为不相等
但如果大小写无关紧要,你只想检查变量的值,可以使用lower.()把变量的值全部转为小写的,值得注意的是,lower()方法不会修改存储在变量中的值,不会影响原来的变量
car='Audi' if car.lower()=='audi': print('great') print(car)
②检查是否不相等
!=
③数值比较
> < == <= >=
检查多个条件:
①使用and检查多个条件
只有and左右两边的条件都成立才为True,为了改善可读性,可将每个条件测试都分别放在一对括号内,但并非必须这样做
②使用or检查多个条件
只要任意一个条件能够满足,即为True
检查特定的值是否在列表中:
要判断特定的值是否在列表中,可使用关键字in
requested_toppings=['mushrooms','onions','pineapple'] if 'mushrooms' in requested_toppings: print('ture')
检查特定的值是否不在列表中:
可以使用关键词not in
banned_users=['andrew','carolina','david'] user='marie' if user not in banned_users: print(f"{user.title()},you can post a response if you want!")
布尔表达式:
布尔表达式u条件表达式一样,布尔表达式的结果要么为True,要么为False
练习5.1
car='subaru' print("Is car=='subaru'? I predict True.") print(car=='subaru')
if-else语句:面临两种可能的情况
age=19 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 your turn 18!")
if-elif-else 语句:面临两种以上可能的情况,可以使用多个elif
age=12 if age<4: price=0 elif age<18: price=25 else: price=40 print(f"Your admission cost is {price} yuan.")
Python并不要求if-elif结构后面必须有else代码块,在一些情况下,else代码块很有用,而在其它情况下,使用一条elif语句来处理特定的情形更清晰
测试多个条件:
requested_toppings=['mushrooms','extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms") if 'extra cheese' in requested_toppings: print("Adding extra cheese") if 'pepperoni' in requested_toppings: print("Adding pepperoni") print("\nFinished making your pizza")
这些if语句会一个一个按顺序执行下去进行判断(多个代码块),如果采用if-elif语句,则只会执行其中一个语句(一个代码块)。
练习5.3
alien_color='green' if alien_color=='red': print("you get five points")
练习5.4
alien_color='red' if alien_color=='green': print("you get five points") else: print("you get ten points")
练习5.5
alien_color='yellow' if alien_color=='green': print("you get five points") elif alien_color=='red': print("you get ten points") else: print("you get fifteen points")
练习5.6
age=19 if age < 2: print("that's a baby") elif 2 <= age < 4: print("that's a little boy") elif 4 <= age <13: print("that's a child") elif 13 <= age<18: print("that's a teenager") elif 18 <= age<65: print("that's a adult") else: print("that's an old")
使用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(f"Adding {requested_topping}") print("\nFinished making your pizza")
确定列表非空:
requested_toppings=[] if requested_toppings: for requested_topping in requested_toppings: print(f"Adding {requested_topping}") print("\nFinished making your pizza!") else: print("Are you sure you want a plain pizza?")
使用多个列表:
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(f"Adding {requested_topping}") else: print(f"Sorry, we don't have {requested_topping}") print("\nFinished making your pizza!")
练习5.8
users=['Join','Mike','admin','Alan','Kobe'] for user in users: if user=='admin': print("Hello admin, would you like to see a status report.") else: print(f"Hello {user}, thank you for logging in again.")
练习5.9:
current_users = ['Join', 'Mike', 'admin', 'Alan', 'Kobe']
new_users = ['Admin', 'Nike', 'adidas', 'Alan', 'duke']
current_users1=[item.lower() for item in current_users]
for new_user in new_users:
if new_user.lower() in current_users1:
print("该昵称已经被占用")
else:
print(f"你的昵称为:{new_user}")
练习5.10
numbers=[1,2,3,4,5,6,7,8,9] for number in numbers: if number==1: print("1st") elif number==2: print("2nd") elif number==3: print("3rd") else: print(f"{number}th")