1.if语句:根据一系列的条件,来判断执行什么操作
#简单例子,检查当前的车是否是bmw,如果是,大写输出,如果不是,首字母大写输出
cars=["audi","benchi","bmw","toyota"]
for car in cars:
if car == "bmw":
print(car.upper())
else:
print(car.title())
Audi
Benchi
BMW
Toyota
2.条件测试:每条if的核心都是一个值为True或False的表达式,称之为条件测试,条件测试值为True,python执行if后面的语句,否则就忽略这些代码。 检查相等用“==”区分大小写 检查不等用“!=”区分大小写有时候检查两个值不相等的效率更高 检查多个条件,用and(and表达式左右两个都要为真),or(左右两边的表达式至少一个为真)
car="bmw" #一个等号是陈述“将变量car的值设置为“bmw””
if car == "bmw":#条件为True #两个等号是发问,“变量car的值是“bmw”吗?”
print(car.upper())#执行
if car == "audi":#条件为False
print(car.upper())#忽略
BMW
my_age = 18
you_age = 22
(my_age > 21) or (you_age > 21)
True
3.检查特定的值是否在列表中,关键词 in,不在列表中 not in
citys=["beijing","shanghai","guangzhou","shenzhen"]
print("beijing" in citys)
city="nanjing"
if city not in citys:
print(city.upper())
True
NANJING
4.if语句,根据测试条件数不同有多种if语句
(1)简单if语句:只有一个测试条件和一个操作
age=19
if age>18:
print("you are enough to vote!")
you are enough to vote!
(2)if-else 语句:测试条件通过时执行if后面语句,没有通过时,执行else后面语句,z总是会执行两者之一
age=15
if age>18:
print("you are enough to vote!")
else:
print("Sorry , you are too young to vote.")
Sorry , you are too young to vote.
(3)if-elif-else结构:检查条件大于两个,一次检查每个条件,直到通过条件测试,执行后面代码,并跳过余下的测试,其中else不是必须的
age=77
if age < 4:
price = 0
elif age < 18:
price = 10
elif age < 65:
price = 10
else:
price = 5
print("you admission cost is $"+str(price)+".")
you admission cost is $5.
5.测试多个条件:以上适用于只要一个测试条件满足,就会跳过余下的测试条件。 有时候必须检查所有条件,这时候需要使用一系列不包含elif的if语句,不管前一个测试是否通过,都将进行这个测试 总之,如果只想执行一个代码块,就使用if-elif-else结构,如果要运行多个代码块,就使用一系列对的if语句
citys=["beijing","shanghai","guangzhou","shenzhen"]
if "beijing" in citys:
print("hello beijing")
if "shanghai" in citys:
print("hello shanghai")
if "nanjing" not in citys:
print("hello nanjing")
hello beijing
hello shanghai
hello nanjing
6.使用if语句来处理列表
request_toppings=["mushrooms","green peppers","extra cheese"]
for request_topping in request_toppings:
if request_topping=="green peppers":
print("sorry, we are out of green peppers right now.")
else:
print("Adding"+request_topping+".")
print("Finished making your pizza!")
Addingmushrooms.
sorry, we are out of green peppers right now.
Addingextra cheese.
Finished making your pizza!
7.对列表进行操作之前,判断列表是否为空很重要
request_toppings=[]
if request_toppings: #测试条件为False,不执行
for request_topping in request_toppings:
if request_topping=="green peppers":
print("sorry, we are out of green peppers right now.")
else:
print("Adding"+request_topping+".")
else:#测试条件为True,执行后面语句
print("Are you sure you want a plain pizza!")
Are you sure you want a plain pizza!