一个简单示例
1.给定一个列表 2.对列表进行遍历 3.判断遍历到为每一个元素是否满足条件, 4.根据判断结果进行打印
#if 语句的简单示范
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw':
print(car.upper()) #如果是宝马就大写输出
else:
print(car.title())
条件测试
这一小结看到 1.检查字符串是否相等,注意大小写,python对大小写敏感,实际应用会将字符统一转为大写或小写或满足一定规范的格式。 2.可以进行数字的比较 3.可以使用关键子and\or 进行多条件判断 and需要全部满足 or只需要满足一个 4 当然也可以判断布尔类型,直接判断即可。
#5.2.1 检查是否相等
car='bmw';
print(car=='bmw') #检查等号两边的值是否相等
#5.2.2 检查是否相等时忽略大小写
#python对字符串大小写敏感
car='AUDI'
print(car=='audi')
#可以统一转化为大写/小写 然后再进行比较
print(car.lower()=='audi')
#5.2.3 检查是否不相等
requested_topping='mushrooms'
if requested_topping!='anchovies':
print("Hold the anchovies!")
#5.2.4数值比较
age=18
print(age==18)
#检查两个数不等
answer=17
if answer!=42:
print("That is not the correct answer.Please try again!")
#检查多个条件
#要检查多个条件 可以使用and关键子将两个测试条件合二为一
age_0=22
age_1=18
print(age_0>=21 and age_1>=21)
age_1=22
print(age_0>=21 and age_1>=21)
#使用or关键字检查多个条件 只要满足其一就可以
age_0=22
age_1=18
print(age_0>=21 or age_1>=21)
age_0=18
print(age_0>=21 or age_1>=21)
#检查特定值是否包含再列表中 可以使用关键字 in
requested_toppings=['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoin' in requested_toppings)
#5.2.7 检察特定值是否包含在列表中
banned_users=['andrew','carolina','david']
user='marie'
if user not in banned_users: #如果user 不在列表中
print(f"{user.title()},you can post a reponse if you wish.")
#5.2.8 布尔表达式
game_active=True
can_edit=False
print(game_active,can_edit)
#Test
cars=['bmw','subaru','audi','benchi']
for car in cars:
if car=='subaru':
print("is car=='subaru'? I predicet Ture.")
if car=='audi':
print(" Is car=='audi'? I predice False.")
else:
print(car.title(),"都不是")
str_1='aaaa'
str_2='bbbb'
print(str_1==str_2,"直接比较")
str_2='Aaaa'
print(str_1.lower()==str_2.lower(),"统一转化为小写 进行比较")
number=20
print(number >=18,"是否成年")
print(number<=30,"而立之年")
print(number>24,"毕业了")
print(number<28,"结婚啦")
print(number>=18 and str_1.lower()=='aaaa',"and 关键字全部满足")
print(number>30 or str_1.lower()=='aaaa',"or 关键子 只要满足一个")
numbers=[value for value in range(1,11)]
print("number",number)
print("numbers",numbers)
print(number in numbers)
if语句
if用于条件判断,可以配合for循环,进行特定数据的定向操作。 if_elif/else 只要条件成立,就会跳过后续判断,所有针对情况,可以选择是并列的if,还是连串的if_elif/else
#if 语句
#5.3.1 简单if语句
age =19
if age>=18:
print('You are old enough to vote!')
age=19
if age>=18:
print('You are old enough to vote!')
print("Have you registered to vote yet?")
#5.3.2 if_else语句
age=17
if age>=18:
print("You are old enougth to vote!")
print("Have you registeed 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 结构
#检查超过两个条件的情况
age=12
if age<4:
print('Your admission cost is $0.')
elif age<18:
print('Your admission cost is $25.')
else:
print('Your admission cost is $40.')
#简洁写法
age=12
if age<4:
price=0
elif age<18:
price=25
else:
price=40
print(f"admission cost is{price}")
#5.3.4 使用多个elif 代码块
age=12
if age<4:
price=0
elif age<18:
price=25
elif age<65:
price=40
else:
price=20
print(f" Your admission cost is{price}")
#python 并不要求if_elif后必须有else
age=12
if age<4:
price=0
elif age<18:
price=25
elif age<65:
price=40
elif age>=65:
price=20
print(f"Your admission cost is {price}")
#5.3.6 测试多个条件
request_toppings=['mushrooms','estra cheese']
if 'mushrooms' in request_toppings:
print('Adding mushrooms.')
if 'pepperoin' in request_toppings:
print('Adding pepperoni.')
if 'extra cheese' in request_toppings:
print('Adding extra cheese.')
print("\n Finished making your pizza!")
#if_else 一旦条件成立,后续的条件就不会判断了
#Test
colors=['green','yellow','red']
score=0
for color in colors:
allien_color = color
if (allien_color == 'green'):
score+=5
print("The allien_color is Green",score)
elif (allien_color=='yellow'):
score+=10
print("The allien_coloe is Green",score)
elif(allien_color=='red'):
score+=15
print('The allien_color is Green',score)
ages=[age for age in range(1,100)]
for age in ages:
if(age<2):
print("这是婴儿",age)
elif(age>=2 and age<4):
print("这是幼儿",age)
elif(age>=4 and age<13):
print("这是儿童",age)
elif(age>=13 and age<20):
print("这是青少年",age)
elif(age>=20 and age<65):
print("这是成年人",age)
else:
print("这是老人",age)
fruits=['🍎','🍍','🍌','🍉']
if '🍎' in fruits:
print("You really like apple")
使用if语句处理列表
关键字 'in'/'not in' 可以直接判断某个元素是否在集合中,再配合if判断条件,可以说是相得益彰。 可以直接使用“if+列表名”进行列表的判空操作
#使用if语句处理列表
#5.4.1检查特殊元素
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("\n Finished making your pizza")
#5.4.2确定列表不是空
requested_toppings=[]
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}." )
print("\n Finished making your pizza!")
else:
print("Are you sure you want a plain pizza?") #证明链表为空
#if语句中将列表名用作条件表达式时,Python将在列表至少包含一个元素时返回True,并在列表为空时,返回False
#5.4.3 使用多个列表
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("\n Finshed making your pizza!")
#Test
persions=['loary','jeckey','polo','bobry','sandery','admin']
if persions:
for persion in persions:
if persion == 'admin':
print("Hello admin,would you like to see a status report?")
else:
print("Hello,thank you for logging in again")
del persions
current_users=['boob','alise','admine','jiao','bish']
new_users=['aaa','bbb','alise','ddd','jiao']
for ne in new_users:
if ne.lower() in current_users:
print("姓名已存在",ne)
else:
print("用户名未使用",ne)
numbers=[val for val in range(1,10)]
for number in numbers:
print(number)
通过对第五章的学习,对if语句的了解,if在判断条件,在for循环中的使用,判断条件的关键字and/or、in/not in ,在列表中的操作,都是非常有用也方便的,无形的透露出,python的简洁、优雅。