if语句
cars = ['audi', 'bmw', 'subaru', 'toyata']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
1.1 条件测试
1.1.1 是否相等
在python中检查是否相等时,会区分大小写,所以可以灵活使用title(),upper(),low()。
if car == 'bmw'
1.1.2 是否不相等
要判断两个值是否不等,可结合使用惊叹号和等号(!=),其中惊叹号表示不等。
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
1.1.3 比较数字
常用符号<, <=, >, >=, =, !=
age = 17
if age == 18:
print("age is 18")
else
print("age is not 18")
1.2 检查多个条件
需要检测两个及以上的条件时,可以使用and
,or
关键字
-
使用and检查多个条件
age = 17 if age >= 21 and age <= 25 print("age is between 21 and 25")
-
使用or检查多个条件
age = 17 if age <=10 or age >=28 print("ok")
1.3 检查特定值是否包含在列表中
-
要判断特定的值是否包含在列表中,可以使用关键字
in
request_toppings = ['mushrooms', 'onions', 'pineapple'] if 'mushrooms' in request_toppings: print("ok")
-
要判断特定值不包含在列表中,可以使用关键字
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.")
1.4 布尔表达式
布尔表达式的结果要么为True, 要么为False
game_active = True
can_edit = False
1.5 if-else语句
经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作,可以使用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!")
经常需要检查超过两个的情形,为此可使用Python提供的if-else-else
结构。
age = 12
if age < 4:
print("Your adminssion cost is $0.")
elif age < 18
print("Your adminssion cost is $5.")
else:
print("Your adminssion cost is $10.")
可以根据实际情况,缺省掉最后的else
age = 12
if age < 4:
...
elif age <10:
...
elif age < 20:
...
1.6 使用if语句处理列表
1.6.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.")
1.6.1 确定列表不为空
requested_toppings = []
if requested_toppings: // 判断列表是否为空
for requested_topping in requested_toppings:
...
...
else:
print("Are you sure you want a plain pizza?")
1.7 良好的格式设置习惯
在诸如 == , >= 等比较运算符两边各加一个空格,这样比较利于阅读代码
网友评论