第五章 if语句

本文详细介绍了Python中的if语句及其各种条件测试,包括相等与不等比较、忽略大小写、数值比较、逻辑运算符的使用,以及在列表中的值判断。此外,还展示了如何通过if-else和if-elif-else结构处理多个条件,并给出了多个练习案例,涉及列表处理和字符串操作。最后强调了if语句的格式规范。

第五章 if语句

5.1简单示例

有四个人,如果是zhangsan,就全大写输出,不是,就首字母大写输出

peoples = ['lisi','zhangsan','wangma','zhaoqian']

for people in peoples:
    if people == 'zhanghsan':
        print(people.upper())
    else:
        print(people.title())
Lisi
Zhangsan
Wangma
Zhaoqian

可以发现python中这些控制语句末尾都跟逗号,直观的就是换行有没有自动缩进

5.2 条件测试

if语句的核心都是一个值为True或者False的表达式,即条件

5.2.1检查是否相等

相等运算符==:两边值相等输出True,否则输出False

=表示赋值,将右侧变量的值赋给左侧

car = 'bmw'
car == 'bmw'
True
car == 'auto'
False

5.2.2检查是否相等时忽略大小写

默认考虑大小写,大小写不同的会输出False,

若不想考虑大小写,可以用方法.lower.upper.title改变来比较,而且不改变原数据

car = 'Bmw'
car == 'bmw'
False
print(car.lower() == 'bmw') 
print(car)   # 并不改变原数据
True
Bmw

5.2.3 检查是否不相等

用符号!=表示不相等

have = 'noodles'

if have != 'cake':
    print("拿上你的蛋糕!")
拿上你的蛋糕!

5.2.4 数值比较

age = 18
age == 18
True
answer = 45
if answer != 20:
    print("你的答案是错的!")
你的答案是错的!

还可以用其他的比较,小于大于,小于等于,大于等于

age = 18
age > 16
True
age <=18
True

5.2.5 检查多个条件(逻辑运算符)

x and y同真为真,其余为假

x or y 同假为假,其余为真

not x 直接否定后面的x,假→真,真→假


1.使用and检查多个条件
age0 = 22
age1 = 26
age0 > 21 and age1 < 25
False
age1 = 24
(age0 > 21) and (age1 < 25) # 可以用括号,更好看
True

2.使用or检查,只要有一个条件满足就通过测试

age0 = 19
age1 = 30
age0 >25 or age1 > 25
True

3.使用not取反(这个反的也是判断条件,不能反值,也能反,默认大于一的数为True)

age0 = 19
# not age0 > 99
not age0
False

5.2.6 检查特定值是否包含在列表中

用关键字in来判断,特定值是否包含在列表中

peoples = ['lisi','zhangsan','wangma','zhaoqian']

'zhaoliu' in peoples
False
'zhangsan' in peoples
True

5.2.7 检查特定值是否不包含在列表中

用if not in 判断

peoples = ['lisi','zhangsan','wangma','zhaoqian']
player = 'wangwu'

if player not in peoples:
    print(f"{player},you are not qualified")
wangwu,you are not qualified

5.2.8 布尔表达式

布尔表达式通常用于记录条件,结果要么为True要么为False,如游戏是否在运行

game_active = True
can_edit = False

5.2.9 练习

5-1 条件测试

language = 'python'
print("Is language == 'python'? I predict True")
print(language == 'python')

print("Is language == 'C++'? I predict True")
print(language == 'C++')
Is language == 'python'? I predict True
True
Is language == 'C++'? I predict True
False

不是返回false,是返回true

5-2 更多条件测试

a = 'Hello'
b = 'hello'
print(a == b)
print(a != b)
print(a.lower() == b)
False
True
True
c = 6
d = 7
print(c > d)
print(c < d)

e = 25
print(c>d and d<e)
print(c>d or d<e)
False
True
False
True
peoples = ['lisi','zhangsan','wangma','zhaoqian']
player = 'keqing'
string1 = 'zhangsan'

print('zhangsan' in peoples)

if player not in peoples:
    print("NO!")
True
NO!

5.3 if语句

5.3.1简单的if语句

最简单的if语句只有一个测试和一个操作

if conditional_test:
(缩进)do something

age = 19

if age >= 18:
    print("你成年了")
    print("你可以当选民了")
你成年了
你可以当选民了

5.3.2 if-else语句

age = 17
if age > 18:
    print("你成年了")
    print("你可以当选民了")
else:
    print("你还没有成年")
    print("快快长大")
        
你还没有成年
快快长大

5.3.3 if-elif-else

多个条件,下面是一个根据年龄段收费的游乐场

age = 12

if age < 4:
    print("免费")
elif age < 18:
    print("门票费25")
else:
    print("门票费50")
门票费25
# 更好的写法,把输出放到外面,if语句只确定值
age = 25

if age < 4:
    price = 0
elif age < 18:
    price = 25
else:
    price = 50
    
print(f"门票费为{price}")
门票费为50

这样写效率更高,也更好修改,比如要修改输出内容,只用修改一句,而不是上面的修改三个print()

5.3.4 使用多个elif代码块

age = 70

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 50
else:
    price = 20
    
print(f"门票费为{price}")
门票费为20

5.3.5 省略else代码块

else作用:在不满足ifelif的条件,其中的代码就会执行,可能引入无效或恶意的数据,若希望指定特定条件,可以用elif结尾

age = 10000000 # 不合逻辑

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 50
else:
    price = 20
    
print(f"门票费为{price}")
门票费为20

5.3.6测试多个条件

if-else语句仅适用于只有一个条件满足的情况,通过后余下的测试会被跳过

若想检查你所有关心的条件可以用一系列if语句

tiaoliao = ["辣椒",'葱花香菜']

if '辣椒' in tiaoliao:
    print("加点辣椒")
if '孜然' in tiaoliao:
    print("放孜然")
if '葱花香菜' in tiaoliao:
    print("放葱花香菜")

    
print("\n您的煎饼果子做好了")
加点辣椒
放葱花香菜

您的煎饼果子做好了
# 如果是if-else语句

tiaoliao = ["辣椒",'葱花香菜']

if '辣椒' in tiaoliao:
    print("加点辣椒")
elif '孜然' in tiaoliao:   # 这不符合直接跳出if语句
    print("放孜然")
else :                     # 这句就不执行了
    print("放葱花香菜")

    
print("\n您的煎饼果子做好了")
加点辣椒

您的煎饼果子做好了

5.3.7 练习

5-3 外星人颜色

ailen_color = 'yellow'

if ailen_color == 'green':
    print("You get 5 point")

print("--------------------")
ailen_color = 'green'

if ailen_color == 'green':
    print("You get 5 point")
--------------------
You get 5 point

5-4 外星人颜色2

ailen_color = 'yellow'

if ailen_color == "green":
    print("你击杀了绿色外星人,获得5分")
else:
    print("你获得了10分")

print("---------------------")
ailen_color2 = 'green'

if ailen_color2 == "green":
    print("你击杀了绿色外星人,获得5分")
else:
    print("你获得了10分")
你获得了10分
---------------------
你击杀了绿色外星人,获得5分

5-5 外星人颜色3

ailen_color = ['yellow','green','red']

for color in ailen_color: # 循环输出
    if color == 'green':
        print("你获得5分")
    elif ailen_color == 'yellow':
        print("你获得10分")
    else:
        print("你获得15分")
你获得15分
你获得5分
你获得15分

5-6 人生的不同阶段

age = 25

if age < 2:
    print("婴儿")
elif age < 4:
    print("幼儿")
elif age < 13:
    print("儿童")
elif age < 20:
    print("青少年")
elif age < 65:
    print("成年人")
else:
    print("老年人")
成年人

5-7 喜欢的水果

favorite_fruit = ['apple','banana','orange']

fruit = 'pear'

if 'apple' in favorite_fruit:
    print("Yes!")
if 'banana' in favorite_fruit:
    print("You really like banana")
if 'orange' in favorite_fruit:
    print("You really like orange")
Yes!
You really like banana
You really like orange

5.4使用if语句处理列表

⭐对列表的值做特殊处理

⭐高效的管理不断变化的情形

5.4.1 检查特殊元素

如果是该元素,则进行操作

tiaoliao = ["辣椒",'葱花','香菜']

for add in tiaoliao:
    if add == '香菜':        # 针对某个元素的操作
        print("不好意思,香菜用完了")
    else:
        print(f"adding {add}")

print("请享用你的煎饼果子")
adding 辣椒
adding 葱花
不好意思,香菜用完了
请享用你的煎饼果子

5.4.2 确定列表不是空的

tiaoliao = []

if tiaoliao:   # 直接以列表名为判断条件,空就是false
    for add in tiaoliao:
        if add == '香菜':        # 针对某个元素的操作
            print("不好意思,香菜用完了")
        else:
            print(f"adding {add}")
else:
    print("你确定你什么都不放吗")
你确定你什么都不放吗
available_tiaoliao = ["辣椒",'葱花','香菜','孜然']
requested_tiaoliao = ['辣椒','葱花','麻酱']

for tiaoliao in requested_tiaoliao:
    if tiaoliao in available_tiaoliao:
        print(f"add{tiaoliao}")
    else:
        print(f"不好意思,我们没有{tiaoliao}")

print("煎饼果子好了!")
add辣椒
add葱花
不好意思,我们没有麻酱
煎饼果子好了!

5.4.4练习

5-8 以特殊方式跟管理员打招呼

users = ['lisi','zhangsan','admin','wangma','zhaoqian']

for use in users:
    if use == 'admin':
        print(f"Hello {use},would you like to see a status report?")
    else:
        print(f"Hello {use},thank you for logging in again.")
Hello lisi,thank you for logging in again.
Hello zhangsan,thank you for logging in again.
Hello admin,would you like to see a status report?
Hello wangma,thank you for logging in again.
Hello zhaoqian,thank you for logging in again.

5-9 处理没有用户的情形

users = []

if users:
    for use in users:
        if use == 'admin':
            print(f"Hello {use},would you like to see a status report?")
        else:
            print(f"Hello {use},thank you for logging in again.")
else:
    print("We need to find some users!")
We need to find some users!

5-10 检查用户名

current_users = ['Lisi','ZHANGsan','admin','wangma','zhaoqian']
new_users = ['keqing','Gongzi','ganyu','zhangSan','Admin']

# 创建current_users的副本,将其全改为小写
current_users1 = current_users[:]
for i in range(len(current_users)):
    current_users1[i] = current_users[i].lower()
print(current_users1)

# 遍历新列表,若相等就输出已被使用
for user in new_users:
    if user.lower() in current_users1:
        print("该用户名已被使用,请输入其他用户名")
    else:
        print("这个用户名未被使用,您可以使用")
['lisi', 'zhangsan', 'admin', 'wangma', 'zhaoqian']
这个用户名未被使用,您可以使用
这个用户名未被使用,您可以使用
这个用户名未被使用,您可以使用
该用户名已被使用,请输入其他用户名
该用户名已被使用,请输入其他用户名

5-11 序数

num = [] 
for i in range(1,10):
    num.append(i)
print(num)

for value in num:
    if value == 1:
        print(f"{value}st\n")
    elif value == 2:
        print(f"{value}nd\n")
    elif value == 3:
        print(f"{value}rd\n")
    else:
        print(f"{value}th\n")
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1st
2nd    
3rd    
4th    
5th    
6th    
7th    
8th    
9th

5.5设置if语句的格式

if age > 4: 加运算符两侧加空格

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值