python u5笔记

第五章 if语句

In [1]:

# if语言让你能够检查程序的当前状态,并采取相应的措施。

# 条件测试。

In [2]:

# eg.对于汽车名‘bmw’,应该以全大写的方式打印。

# 遍历这个列表,并以首字母大写的方式打印其中的汽车名,不过对于‘bmw’,则以全大写的方式打印。

cars = ['audi','bmw','lexus','cadillac']

for car in cars:

    if car == 'bmw':

        print(car.upper())

    else:

        print(car.title())

Audi

BMW

Lexus

Cadillac

In [3]:

# 条件测试:每条if语句的核心都是指为True或False的表达式,这种表达式称为条件测试。

In [4]:

# 如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;

# 如果为False,Python就忽略这些代码。

5.2.1 检查是否相等

In [5]:

car = 'bmw'

car =='bmw'

Out[5]:

True

In [6]:

# 首先使用一个等号,将car的值设置为'bmw';

# 然后使用两个等号检查car的值是否为'bmw';

# 相等时返回为True,否则为False。

In [7]:

car = 'audi'

car == 'bmw'

Out[7]:

False

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

In [8]:

# 在python中检查是否相等时区分大小写.

In [9]:

car = 'Audi'

car == 'audi'

Out[9]:

False

In [10]:

# 但如果大小写无关紧要之相检查变量的值,可将变量的值转换为小写,再进行比较:

car ='Audi'

car.lower() == 'audi'

Out[10]:

True

In [11]:

# 函数lower()不会修改最初赋给变量car的值,因此进行这样的比较时不会影响原来的变量:

car = 'Audi'

car.lower() == 'audi'

car

Out[11]:

'Audi'

In [12]:

# 网站采用类似的方法,让用户输入的数据符合特定的格式。

# 例如网站可能使用类似的测试来,确保用户名是独一无二的。

# 如果已经有用户名“John”(不管大小写如何),则用户“John”提交用户名时将遭到拒绝。

5.2.3 检查是否不相等

In [13]:

# 要判断两个人是否不等,可结合使用惊叹号和等号(!=),其中的!惊叹号表示不,其他很多编程语言中也是如此。

In [14]:

# eg.将把要求的比赛配料付给一个变量,再打印一条信息,指出顾客要求的配料是否是意式小银鱼(anchovies):

requested_topping = 'mushrooms'

if requested_topping != 'anchovies':        # if语句记得加冒号

    print("Hold the anchovies!")            # 即不要加

# 如果这两个值不相等,即不要加,Python将返回True,进而执行紧跟在if语句后面的代码;

# 如果相等,即要加,Python酱将返回False,因此不执行紧跟在if语句后面的代码。

Hold the anchovies!

5.2.4 数值比较

In [15]:

age = 18

age == 18

Out[15]:

True

In [16]:

answer = 17

if answer != 42:

    print("That is not the correct answer.Please try again!")

That is not the correct answer.Please try again!

In [17]:

# 在if语句中可使用各种数学比较。

age = 19

age < 21

Out[17]:

True

In [18]:

age <=21

Out[18]:

True

In [19]:

age > 21

Out[19]:

False

In [20]:

age >= 21

Out[20]:

False

5.2.5 检查多个条件

In [21]:

# 同时检查多个条件可以用关键字and和or。

①使用and检查多个条件:

In [22]:

# 如果每个测试都通过了,整个表达式就为True;

# 如果至少一个测试没有通过,整个表达式就为False。

age_0 = 22

age_1 = 18

age_0 >= 21 and age_1 >= 21

Out[22]:

False

In [23]:

age_1 = 22

age_0 >= 21 and age_1 >=21

Out[23]:

True

In [24]:

# 为改善可读性可将每个测试分别放在一对圆括号内,但并非必须这样做。

(age_0 >= 21) and (age_1 >=21)

Out[24]:

True

②使用or检查多个条件:

In [25]:

# 关键词or也能够让你检查多个条件,但只要至少一个条件满足,就能通过整个测试。

# 仅当两个测试都没有通过时使用or的表达式才为False。

age_0 = 22

age_1 = 18

age_0 >= 21 or age_1 >= 21

Out[25]:

True

In [26]:

age_0 = 18

age_0 >= 21 or age_1 >= 21

Out[26]:

False

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

In [27]:

# 有时候执行操作前必须检查列表是否包含特定的值。

# 例如结束用户的注册过程前,可能需要检查他提供的用户名是否已包含在用户列表中。

# 在地圖程序中,可能需要检查用户提交的位置是否包含在已知位置列表中。

requested_toppings = ['mushrooms','onions','pineapple']

'mushrooms' in requested_toppings

Out[27]:

True

In [28]:

'pepperoni' in requested_toppings

Out[28]:

False

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

In [29]:

# 有些时候确定特定的值未包含在列表中很重要。

# 可使用关键字not in。

# 其中包含被禁止在论坛上发表评论的用户,可以在允许用户提交评论前检查他是否被禁言.

banned_users = ['alkaid', 'amy', 'sarah']

user = 'laura'

if user not in banned_users:

    print(f"{user.title()},you can post a response if you wish.")

# 如果user的值未包含在banned_users中,Python将返回True。

# 由于用户群“laura”未包含在banned_users中,因此他将看到一条邀请他发表评论的消息。

Laura,you can post a response if you wish.

5.2.8 布尔表达式(即条件测试)

5.3 if语句

if conditional_test: \n do something

In [30]:

# 假设有一个表示某人年龄的变量,而你想知道这个人是否符合投票的年龄:

age = 19

if age >= 18:

    print("You are old enough to vote!")

You are old enough to vote!

In [31]:

age = 19

if age >= 18:

    print("You are old enough to vote!")

    print("Have you registered to vote yet?")

# 条件测试通过了,而且两个函数调用print()都缩进了,因此他们都将执行:

You are old enough to vote!

Have you registered to vote yet?

In [32]:

# 如果age的值小于18,则这个程序将不会有任何输出。

5.3.2 if-else语句

In [33]:

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

Sorry, you are too young to vote.

Please register to vote as soon as you turn 18!

5.3.3 if-elif-else结构

In [34]:

# 用于检查超过两个的情形。

In [35]:

age = 12

if age < 4:

    print("Your admission cost is $0.")

elif age < 18:

    print("Your admission cost is $1.")

else:

    print("Your admission cost is $2.")

# 注意冒号;缩进

Your admission cost is $1.

In [36]:

# 为了让代码更简洁。

age = 12

if age < 4:

    price = 0

elif age < 18:

    price = 1

else:

    price =2

    

print(f"Your admission cosgt is ${price}.")

Your admission cosgt is $1.

5.3.4 使用多个elif代码块

In [37]:

age = 12

if age < 4:

    price = 0

elif age < 18:

    price = 1

elif age < 65:

    price = 2

else:

    price = 1.5

    

print(f"Your admission cosgt is ${price}.")

Your admission cosgt is $1.

5.3.5 省略else代码块

In [38]:

# Python并不要求if-elif结构后面必须有else代码块。

In [39]:

age = 12

if age < 4:

    price = 0

elif age < 18:

    price = 1

elif age < 65:

    price = 2

elif age>= 65:          #else:

    price = 1.5

    

print(f"Your admission cosgt is ${price}.")

Your admission cosgt is $1.

5.3.6 测试多个条件

In [40]:

# 应使用一系列简单if语句,不包含elif和else代码块。

# 在可能有多个条件为True,且需要在每个条件为True时都采取相应措施

# eg.如果顾客点了两种配料:

requested_toppings = ['mushrooms','pineapple']    #点了两种配料,2个元素,(顾客)[可变]

if 'mushrooms' in requested_toppings:

    print("Adding mushrooms.")

if 'onions' in requested_toppings:

    print("Adding onions.")

if 'pineapple' in requested_toppings:

    print("Adding pineapple.")                     #3个条件,(商家)

print("\nFinished making your pizza!")

Adding mushrooms.

Adding pineapple.

Finished making your pizza!

In [41]:

# 使用if-elif-else结构,代码将不能正确运行,因为有一个测试通过后,就会跳过余下的测试:

requested_toppings = ['mushrooms','pineapple']    

if 'mushrooms' in requested_toppings:

    print("Adding mushrooms.")

elif 'onions' in requested_toppings:            #对比

    print("Adding onions.")

elif 'pineapple' in requested_toppings:         #对比

    print("Adding pineapple.")                    

print("\nFinished making your pizza!")

Adding mushrooms.

Finished making your pizza!

In [42]:

# 结果是,将添加顾客点的第一种配料,但不会添加其他配料。

In [43]:

# 总之,如果只想执行一个代码块,就使用if-elif-else结构;

# 如果要执行多个代码块,就应使用一系列独立的if语句。

5.4 使用if语句处理列表

①检查特殊元素

In [44]:

requested_toppings = ['mushrooms','onions','pineapple']

for requested_topping in requested_toppings:

    print(f"Adding {requested_topping}.")

print("\nFinished making you pizza!")

Adding mushrooms.

Adding onions.

Adding pineapple.

Finished making you pizza!

In [45]:

# eg.如果比萨店的青椒用完了,可在for循环中包含一条if语句:

requested_toppings = ['mushrooms','cheese','pineapple']

for requested_topping in requested_toppings:

    if requested_topping == 'cheese':

        print("Sorry,we are out of cheese right now.")

    else:

        print(f"Adding {requested_topping}.")

print("\nFinished making you pizza!")

Adding mushrooms.

Sorry,we are out of cheese right now.

Adding pineapple.

Finished making you pizza!

②确定列表不是空的

In [46]:

requested_toppings = []

if requested_toppings:

    for requested_topping in requested_toppings:

        print(f"Adding {requested_toppings}.")

    print("\nFinished making your pizza.")

else:

    print("Are you sure you want a plain pizza?")

# 在这里,这个列表为空:

Are you sure you want a plain pizza?

③使用多个列表

In [47]:

# 如何拒绝怪异的配料要求:

available_toppings = ['mushrooms','olives','peppers','pepperoni','pineapple','extra cheese']

requested_toppings = ['mushrooms','french fried','extra cheese']

for requested_topping in requested_toppings:

    if requested_topping in available_toppings:

        print(f"Adding {requested_toppings}.")

    else:

        print("Sorry,we dont have {requested_topping}.")

print("\nFinished making your pizza.")

Adding ['mushrooms', 'french fried', 'extra cheese'].

Sorry,we dont have {requested_topping}.

Adding ['mushrooms', 'french fried', 'extra cheese'].

Finished making your pizza.

5.5 设置if语句格式

In [48]:

# PEP8提供的建议是:在==、>=、<=等比较运算符号两边各添加一个空格。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值