【Python】Python基础内容笔记整理3:条件测试、简单if语句、复合if语句

免费的清晰思维导图见上传资源压缩包,不需要积分,所有学习章节内容在Python学习专栏中可以找到。

目录

 1 条件测试

1.1 基本概念

1.2 比较运算符

1.3 检查多个条件

1.4 判断特定值是否包含在列表中

1.5 布尔表达式

2 if语句

2.1 简单的if语句

 2.2 if-else语句

2.3 if-elif-else语句

2.4 使用多个elif代码块

2.5 if-elif代码块(省略else)

2.6 多个if语句(测试多个条件)

3 使用if语句处理列表

3.1 检查列表中的特殊元素

3.2 确定列表不为空

3.3 使用多个列表

4 课后题


 1 条件测试

1.1 基本概念

(1)每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。

(2)A=B:给A赋B的值

         A==B:检测A是否与B相等

(3)在Python中检查是否相等时会区分大小写,两个大小写不同的值会被视为不相等。

         如果大小写无关紧要,只想检查变量的值,可以使用.title()、.upper()、.lower()将变量的值转化再进行比较。

         lower()、upper()、title()并不会修改存储在变量中的值,这些函数使用后并不会修改在变量中存储的值,条件测试也不会影响存储在变量中的值,因此进行这样的比较时不会影响原来的变量。

>>>car = 'Audi'
>>>car.lower() == 'audi'
True
>>>car
'Audi'

1.2 比较运算符

比较两个值的关系
检查是否相等(相等运算符)==
检查是否不等(不等运算符)!=
小于<
小于等于<=
大于>
大于等于>=

1.3 检查多个条件

检查多个条件
使用条件
and两个条件都满足,输出为True;其中任意一个不满足,输出为False
or两个条件至少一个满足,输出为True;两个都不满足,输出为False

 为了提高可读性,可以将条件用一对括号括起来:

age_0 = 22
age_1 = 18

age_0 >= 21 and age_1 >=21
>>False

#为了提高可读性,可以将条件用一对括号括起来,例如:
(age_0 >= 18) and (age_1 >=18)
>>True

1.4 判断特定值是否包含在列表中

检查特定值是否包含在列表中
使用条件
in判断特定值是否已包含在列表中
not in判断特定值是否未包含在列表中
banned_users = ['andrew','carolina','david']
users = ['marie','andrew','andi']

for user in users:
    if user in banned_users:
        print(user.title() + ",you can't post a response if you wish.")
    
    #这里也可以用else,但是为了展示not in的用法我没有用else
    if user not in banned_users:
        print(user.title() + ",you can post a response if you wish.")

>>Marie,you can post a response if you wish.
Andrew,you can't post a response if you wish.
Andi,you can post a response if you wish.

1.5 布尔表达式

(1)布尔表达式,别名条件测试。

(2)布尔表达式(Bool)只有两个结果,即True和False。在跟踪程序状态或程序中重要的条件方面,布尔值提供了一种高效的方式。

2 if语句

2.1 简单的if语句

if conditional_test:
    do something

(1)在第一行中可以包含任何条件测试,而在紧跟其后被缩进的代码中,可执行任何操作。若条件测试结果为True,Python就会执行紧跟在if语句后的代码,否则Python将会忽略这些代码。

(2)if语句中缩进的作用于for循环中相同

 2.2 if-else语句

在条件测试通过时执行一个操作,在没有通过时执行另一个操作。 

if conditional_test:
    do something
else:
    do something

2.3 if-elif-else语句

当需要检查超过两个时,可以使用if-elif-else语句。

if conditional_test_01:
    do something
elif conditional_test_02:
    do something
else:
    do something

此处,elif代码行其实是另一个if测试,它仅在前面的if测试未通过时才会运行。 

2.4 使用多个elif代码块

 可以根据需要使用数量的elif代码块。

if conditional_test_01:
    do something
elif conditional_test_02:
    do something
elif conditional_test_03:
    do something
else:
    do something

2.5 if-elif代码块(省略else)

 Python并不要求if-elif结构后面必须有else代码块,有些情况下只是用if-elif结构更简单方便。

else是一条包罗万象的语句,只要不满足任何if或者elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至很多而已数据。如果知道最终要测试的条件,那么使用一个elif代码块来代替else代码块,这样可以肯定仅当满足elif语句条件时,所属的代码块才会执行。

if conditional_test_01:
    do something
elif conditional_test_02:
    do something
elif conditional_test_03:
    do something

2.6 多个if语句(测试多个条件)

if-elif-else结构会在通过测试后跳过余下的测试,所以,当需要检查多个条件时,应该包括一系列不包含elif和else代码块的简单if语句。 

if conditional_test_01:
    do something
if conditional_test_02:
    do something
if conditional_test_03:
    do something

 if-elif-else仅适用于只有一个条件满足的情况:遇到通过了的测试后,Python就会跳过余下的测试。所以如果只想执行一个代码块,就使用if-elif-else结构如果需要运行多个代码块,就需要使用一系列独立的if语句,检查需要检测的所有条件。此时不管前面的if的测试结果如何,都会执行接下来的全部代码,程序运行时会进行多个独立测试。

3 使用if语句处理列表

3.1 检查列表中的特殊元素

list_name = ['element_01','element_02','element_03']

for element_name in list_name:
    if element_name == 'element_01':
        do something
    else:
        do something

3.2 确定列表不为空

#创建一个空列表
list_name = []

#验证列表是否为空
if list_name:
    #若列表不为空
    for element_name in list_name:
        do something
#若列表为空
else:
    do something

3.3 使用多个列表

#定义若干列表
#若某个列表元素固定,也可定义为元组
list_01 = ['element_01','element_02','element_03']
list_02 = ['element_4','element_05']

#遍历list_02
for element_name in list_02:
    #若list_02中的元素在list_01中
    if element_name in list_01:
        do something
    #若list_02中的元素不在list_01中
    else:
        do something

4 课后题

具体题目都打在了注释中。

#课本例题5-1 if语句
#cars.py
print("\n课本例题5-1")
cars = ['audi','bmw','subaru','toyota']

for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

#课本例题5-2 条件测试
#toppings.py
print("\n课本例题5-2")
requested_topping = 'mushrooms'

if requested_topping != 'anchovies':
    print("Hold the anchovies!")

#magic_number.py
answer = 17

if answer != 42:
    print("That is not the correct answer.Please try again!")

#banned_users.py
banned_users = ['andrew','carolina','david']
users = ['marie','andrew','andi']

for user in users:
    if user in banned_users:
        print(user.title() + ",you can't post a response if you wish.")
    if user not in banned_users:
        print(user.title() + ",you can post a response if you wish.")

#课后习题5-1 条件测试:编写一系列条件测试:将每个测试以及你对其结果的预测和实际结果都打印出来,类似于书中例题
#研究清楚为何输出True和False,并创建至少10个测试,且其中结果分别位5个True和5个False
print("\n课后习题5-1")
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')

print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')

#课后习题5-2 更多的条件测试
print("\n课后习题5-2")
#检查两个字符串相等和不等
string_1 = 'abc'
string_2 = 'def'
if string_1 == string_2:
    print("string_1 == string_2")
else:
    print("string_1 != string_2")
#使用函数lower()的测试
name_1 = 'John'
name_2 = 'john'
if name_1.lower() == name_2.lower():
    print("name_1 == name_2")
else:
    print("name_1 != name_2")
#检查两个数字相等、不等、大于、小于、大于等于和小于等于
number_1 = 23
number_2 = 22
if number_1 == number_2:
    print("number_1 == number_2")
if number_1 != number_2:
    print("number_1 != number_2")
if number_1 > number_2:
    print("number_1 > number_2")
if number_1 < number_2:
    print("number_1 < number_2")
if number_1 >= number_2:
    print("number_1 >= number_2")
if number_1 <= number_2:
    print("number_1 <= number_2")
#使用关键字and和or的测试
age_1 = 22
age_2 = 18
if (age_1 >= 21) and (age_2 >= 21):
    print("age_1 and age_2 >= 21")
else:
    print("age_1 and age_2 not >= 21")
if (age_1 >= 21) or (age_2 >= 21):
    print("age_1 or age_2 >= 21")
#测试特定值是否包含在列表中
list_1 = ['anne','ann','cindy']
names = ['anne','david']
for name in names:
    if name in list_1:
        print("the name (" + name.title() + ") in the list_1")
    # 测试特定值是否未包含在列表中
    if name not in list_1:
        print("the name (" + name.title() + ") not in the list_1")

#课本例题5-3 if语句
print("\n课本例题5-3")
#voting.py
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.")
    print("Please register to vote as soon as you turn 18!")
#amusement_park.py
age = 12
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + ".")

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5
print("Your admission cost is $" + str(price) + ".")

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
elif age >= 65:
    price = 5
print("Your admission cost is $" + str(price) + ".")

#toppings.py
requested_toppings = ['mushrooms','extra cheese']

if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
    print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
    print("Adding extra cheese.")

print("\nFinished making your pizza!")

#课后习题5-3 外星人颜色#1:假设在游戏中刚射杀了一个外星人,请创建一个名位alien_color的变量,并将其设置为'green'、'yellow'或‘red'
print("\n课后习题5-3")
alien_color = 'yellow'
#编写一条if语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了5个点
if alien_color == 'green':
    print("Player got 5 point!")
#编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过时没有输出)
if alien_color == 'yellow':
    print("Player got 10 point!")
if alien_color == 'red':
    print("Player got 15 point!")

#课后习题5-4 外星人颜色#2:如练习5-3一样设置外星人的颜色,并编写一个if-else结构
print("\n课后习题5-4")
alien_color = 'yellow'
#如果外星人时绿色的,就打印一条消息,指出玩家因射杀该外星人获得了5个点
if alien_color == 'green':
    print("Player got 5 point!")
#如果外星人不是绿色的,就打印一条消息,指出玩家获得了10个点
else:
    print("Player got 10 point!")
#编写这个程序的两个版本,在一个版本中执行if代码块,而在另一个版本中执行else代码块
if alien_color == 'yellow':
    print("Player got 5 point!")
else:
    print("Player got 10 point!")

#课后习题5-5 外星人颜色#3:将练习5-4中的if-else结构改为if-elif-else结构
print("\n课后习题5-5")
alien_color = 'yellow'
#如果外星人时绿色的,就打印一条消息,指出玩家获得了5个点
if alien_color == 'green':
    print("Player got 5 point!")
#如果外星人是黄色的,就打印一条消息,指出玩家获得了10个点
elif alien_color == 'yellow':
    print("Player got 10 point!")
#如果外星人是红色的,就打印一条消息,指出玩家获得了15个点
else:
    print("Player got 15 point!")

#课后习题5-6 人生的不同阶段:设置变量age的值,再编写一个if-elif-else结构,根据age的值判断处于人生哪个阶段
print("\n课后习题5-6")
age = 23
#如果一个人年龄小于2岁,就打印一条消息,指出她是婴儿
if age < 2:
    print("She is a baby.")
#如果一个人的年龄为2~4岁,就打印一条消息,指出她正蹒跚学步
elif age < 4:
    print("She is taking a baby step.")
#如果一个人的年龄为4~13岁,就打印一条消息,指出她是儿童
elif age < 13:
    print("She is a child.")
#如果一个人的年龄为13~20岁,就打印一条消息,指出她是青少年
elif age < 20:
    print("She is a younger.")
#如果一个人的年龄为20~65岁,就打印一条消息,指出她是成年成
elif age < 65:
    print("She is a adult.")
#如果一个人的年龄超过65岁,就打印一条消息,指出她是老年人
else:
    print("She is an older.")

#课后习题5-7 喜欢的水果:创建一个列表,其中包含你喜欢的水果,再编写一系列独立的if语句,检查列表中是否包含特定的水果
print("\n课后习题5-7")
#将该列表命名为favorite_fruits,并在其中包含三种水果
favorite_fruits = ['mango','cherry','pitaya']
#编写5条if语句,每条都检查某种水果是否包含再列表中,如果包含在列表中,就打印一条消息,如"You really like bananas!"
if 'mango' in favorite_fruits:
    print("You really like mango!")
if 'cherry' in favorite_fruits:
    print("You really like cherry!")
if 'pitaya' in favorite_fruits:
    print("You really like pitaya!")
if 'banana' in favorite_fruits:
    print("You really like banana!")
if 'apple' in favorite_fruits:
    print("You really like apple!")

#课本例题5-4 使用if语句处理列表
print("\n课本例题5-4")
#toppings.py
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")

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!")

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?")

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("Adding " + requested_topping + ".")
    else:
        print("Sorry,we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")

#课后习题5-8 以特殊方式跟管理员打招呼:创建一个至少包含5个用户名的列表,且其中一个用户名为'admin'
#想象你要编写代码,在每位用户登录网站后都打印一条问候消息
print("\n课后习题5-8")
#遍历整个用户列表,并向每位用户打印一条用户消息
user_names = ['admin','amy','anne','benny','john']
for user_name in user_names:
    #如果用户名为'admin',就打印一条特殊的问候消息,如'Hello admin,would you like to see a status report?'
    if user_name == 'admin':
        print("Hello admin,would you like to see a status report?")
    #否则,打印一条普通的问候消息,如'Hello Eric,thank you for logging in again.'
    else:
        print("Hello " + user_name.title() + ",thank you for logging in again.")

#课后习题5-9 处理没有用户的情形:在为完成练习5-8编写的程序中,添加一条if语句,检查用户名列表是否为空
print("\n课后习题5-9")
user_names = ['admin','amy','anne','benny','john']
if user_names:
    for user_name in user_names:
        # 如果用户名为'admin',就打印一条特殊的问候消息,如'Hello admin,would you like to see a status report?'
        if user_name == 'admin':
            print("Hello admin,would you like to see a status report?")
        # 否则,打印一条普通的问候消息,如'Hello Eric,thank you for logging in again.'
        else:
            print("Hello " + user_name.title() + ",thank you for logging in again.")
#如果列表为空,就打印消息"We need to find some users!"
else:
    print("We need to find some users!")
#删除列表中的所有用户名,确定将打印正确的消息
del user_names[:]
if user_names:
    for user_name in user_names:
        # 如果用户名为'admin',就打印一条特殊的问候消息,如'Hello admin,would you like to see a status report?'
        if user_name == 'admin':
            print("Hello admin,would you like to see a status report?")
        # 否则,打印一条普通的问候消息,如'Hello Eric,thank you for logging in again.'
        else:
            print("Hello " + user_name.title() + ",thank you for logging in again.")
#如果列表为空,就打印消息"We need to find some users!"
else:
    print("We need to find some users!")

#课后习题5-10 检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名都是独一无二的
print("\n课后习题5-10")
#创建一个至少包含5个用户名的列表,并将其命名为current_users
current_users = ['admin','amy','anne','benny','john']
#再创建一个包含5个用户名的列表,并将其明明为new_users,并确保其中有一两个用户名也包含在列表current_users中
new_users = ['admin','ann','anne','bosco','july']
#遍历列表new_users,对于其中的每个用户名,都检查它是否已被使用
for new_user in new_users:
    #如果已被使用,就打印一条消息,指出需要输入别的用户名
    if new_user in current_users:
        print("Please input other user name.")
    #否则,打印一条消息,指出这个用户名未被使用
    else:
        print("The user name is not in use.")
#确保比较时不区分大小写,换句话说:如果用户名'John'已被使用,应拒绝用户名'JOHN'
current_users = ['Admin','AMY','Anne','benny','JOHN']
new_users = ['admin','ann','anne','bosco','john']
for new_user in new_users:
    for current_user in current_users:
        if new_user.lower() == current_user.lower():
            print("Please input other user name.")
        else:
            print("The user name is not in use.")

#课后习题5-11 序数:序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外
print("\n课后习题5-11")
#在一个列表中存储数字1~9
numbers = [value for value in range(1,10)]
#遍历这个列表
for number in numbers:
    #在循环中使用一个if-elif-else结构,以打印每个数字对应的序数。
    #输出内容应未1st、2nd、3rd、4th、5th、6th、7th、8th和9th,但每个序数都独占一行
    if number == 1:
        symbol_name = 'st'
    elif number == 2:
        symbol_name = 'nd'
    elif number == 3:
        symbol_name = 'rd'
    else:
        symbol_name = 'th'
    print(str(number) + symbol_name)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值