第五章 if 语句

简单示例

在遍历一些汽车名称的时候大多数都是以小写来写,有一些是用大写来写,这时候就可以使用if语句来编写


cars=['audi','bmw','subaru','toyota']
for car in cars:
    if car=='bmw':
        print(car.upper())
    else:
        print(car.title())
    '''
Audi
BMW
Subaru
Toyota

    '''

条件测试(布尔表达式)

检查是否相等

大多数条件测试都将变量的当前值同特定值进行比较,最简单的条件测试检查变量的值与特定值是否相等

num = '123'
 
print(num == '123')
#True

检查是否相等时不考虑大小写

在Python中大小写不一致的会判定为不相等,如果检查变量的量大小写一般无关紧要的时候就可以使用.lower(),将变量转化为小写再进行比较。

name = "Tom"
 
print(name.lower() == 'tom')
#True

检查是否不相等

要判断两个值是否相等可以结合使用感叹号和等于号,如果相等会输出false,如果不相等会输出true

student_name = "Alex"
 
if student_name != "Tom":
 
    print("my name isn't Tom")
    #True

比较数字

在if语句中执行各种数字比较就会能够直接检查关心的条件。

num = 5
 
print(num < 8)
 
print(num <= 8)
 
print(num > 8)
 
print(num >= 8)
'''
True
 
True
 
False
 
False
'''

检查多个条件

使用and 检查多个条件

要检查两个条件是否都为true可以使用关键字and将两个条件测试合二为一,如果每个测试都通过了,则整个表达式都为true,如果至少有一个测试没有通过就会显示false

age_0 = 22
 
age_1 = 18
 
bool_0 = age_0 >=21 and age_1 >=21
 
print(bool_0)
 
age_1 = 23
 
bool_0 = age_0 >=21 and age_1 >=21
 
print(bool_0)
#False
#True

使用or 检查多个条件

关键字or只要至少有一个条件满足,就能通过整个测试;只有当两个测试都没有通过时,使用or的表达式才为False。

age_0 = 18
 
age_1 = 23
 
bool_0 = age_0 >=21 or age_1 >=21
 
print(bool_0)
#True

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

关键字in让Python检查列表requesteds是否包含onions。另外使用not in可以检查列表是否不包含在列表中。

requesteds = ['mushrooms', 'onions', 'pineapple']
 
print('onions' in requesteds)
 
print('onions' not in requesteds)

if语句

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

input=int(input("请输入一个数字:"))
num=input
if num==10:
    print("正确")

if-else语句

input=int(input("请输入一个数字:"))
num=input
if num==10:
    print("正确")
else:
    print("错误")

if-elif-else语句

input=int(input("请输入年龄:"))
num=input
if num<=12 and num>=6:
    print("半票")
elif num<6:
    print("免费")
else :
    print("全票")

使用多个elif代码块

input=int(input("请输入年龄:"))
num=input
if num<=12 and num>=6:
    print("半票")
elif num<6:
    print("免费")
elif num>12 and num<18:
    print("学生票")
else :
    print("全票")
必要时可以省略else代码

总之如果你想要执行一个代码块就使用if-elif-else结构,如果要运行多个代码块,就要使用一系列的独立的if语句。

使用if语句处理列表

检查特殊元素

requested_items = ["apple", "banana", "orange"]
for requested_item in requested_items:
    print("Adding" + requested_item + "to the shopping cart.")
print("\nFinished adding items to the shopping cart.")
'''
Addingappleto the shopping cart.
Addingbananato the shopping cart.
Addingorangeto the shopping cart.

Finished adding items to the shopping cart.

'''

如果有东西用完了就可以在for循环后面加一条if语句

requesteds = ['mushrooms', 'onions', 'green peppers','pineapple']
 
##if requesteds:##判断列表不是空的
 
for requested in requesteds:
 
    if requested == 'green peppers':
 
        print("Sorry, we are out of green peppers right now.")
 
    else:
 
        print("Adding " + requested + ".")
 
print("\nFinished making your pizza!")
'''
Adding mushrooms.
 
Adding onions.
 
Sorry, we are out of green peppers right now.
 
Adding pineapple.
 
 
 
Finished making your pizza!
'''

确定列表不是空的

到目前为止,对于处理的每个列表都做了一个简单的假设,即假设它们都至少包含一个元素。我们马上就要让用户来提供存储在列表中的信息,因此不能再假设循环运行时列表不是空的。有鉴于此,在运行for循环前确定列表是否为空很重要。

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?")
    #Are you sure you want a plain pizza?

使用多个列表

面的示例定义了两个列表,其中第一个列表包含披萨店供应的配料,而第二个列表包含顾客点的配料。这次对于requested_toppings中的每个元素,都检查它是否是披萨店供应的配料,再决定是否在披萨中添加它:

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!")
'''
Adding mushrooms.
 
Sorry, we don't have french fries.
 
Adding extra cheese.
 
 
 
Finished making your pizza!
'''

本章的每个示例都展示了良好的格式设置习惯。在条件测试的格式设置方面, PEP 8提供的唯一建议是,在诸如==、 >=和<=等比较运算符两边各添加一个空格,例如, if age < 4:要比if age<4:好。

这样的空格不会影响Python对代码的解读,而只是让代码阅读起来更容易。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值