zoukankan      html  css  js  c++  java
  • python编程:从入门到实践----第五章>if 语句

    一、一个简单示例

      假设有一个汽车列表,并想将其每辆汽车的名称打印出来。遇到汽车名‘bmw’,以全大写打印;其他汽车名,首字母大写

    cars=['audi','bmw','subaru','toyota']
    for car in cars:
        if car == 'bmw':     #检查汽车名是否是bmw
            print(car.upper())
        else:
            print(car.title())
    
    #输出结果:
    Audi
    BMW
    Subaru
    Toyota
    

    二、条件测试

      if 语句的核心都有一个值为True或False的表示式。如果条件测试的值为True,就执行if 语句后面的代码;如果为False,就忽略这些代码。

    1. 检查是否相等

    >>>car = 'bmw'    #将car的值设置为bmw
    >>>car =='bmw'    #使用两个等号检查car的值是否为bmw。如果是,返回True;如果不是,返回False
      True

    2. 检查是否等于时不考虑大小写:python检查是否等于时区分大小写

    >>>car = 'Audi'             #将Audi存储在变量car中
    >>>car.lower()=='audi'     #获取变量car的值并将其转换为小写,再将结果与字符串‘audi’进行比较。
    True     
    >>>car
       'Audi'          #这个条件测试并没有影响存储在变量car中的值
    

    3. 检查是否不相等:用(!=)来判断两个值是否不等

    requested_topping = 'mushrooms'
    if requested_topping != 'anchovies':
        print("Hold the anchovies!")
    #输出结果:
    Hold the anchovies!
    

    4. 比较数字

    >>>age = 18
    >>>age == 18
        True             #比较相等,返回True
    
    
    
    answer = 17
    if answer !=42:              #判断两个数字是否不等,如不等打印下面消息
        print("That is not the correct answer.Please try again!")
    
    
    >>>age = 19
    >>>age < 21
    True
    >>>age <=21
    True
    >>>age > 21
    False
    >>>age >=21
    False
    

    5. 检查多个条件  

    a. 使用and检查多个条件:检查两个条件是否都为True,如果是,整个表达式为True;反之如果有一方不是True,整个表达式就为False。

    >>>age_0 = 22         #定义变量age_0和age_1
    >>>age_1 =18
    >>>age_0 >=21 and age_1 >=21        #检查这两个变量是否都大于或等于21
        False                           # 两个变量有一个不符合条件,表达式结果为False
    >>>age_1 =22                 #把age_1的的值修改之后,符合条件,表达式结果为True
    >>>age_0 >=21 and age_1 >=21
        True                    

    b. 使用 or 检查多个条件:只要至少一个条件满足,就能通过整个测试。仅当两个测试都没有通过时,使用or的表达式才为False。

    >>> age_0 =22
    >>> age_1 =18
    >>> age_0 >=21 or age_1 >=21
        True
    >>> age_0 =18
    >>> age_0 >=21 or age_1 >=21
        False
    

    6. 检查特定值是否包含在列表中:要判断特定的值是否已包含在列表中,使用关键字 in。

    >>> requested_toppings = ['mushrooms', 'onions', 'pineapple'] 
    >>> 'mushrooms' in requested_toppings 
        True 
    >>> 'pepperoni' in requested_toppings 
        False

    7. 检查特定值是否不包含在列表中:要判断特定的值不包含在列表中,使用not in。

    banned_users = ['andrew','carolina','david']
    user = 'marie'                 
    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.
    # user的值未包含在列表banned_users中,python将返回True,进而执行缩进的代码行

    8. 布尔表达式:与条件表达式一样,结果不是True,就是False

    game_active = True
    can_edit = False
    
    #布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容
    

      

    三、if 语句

    1. 简单的if 语句:在if 语句中,缩进的作用域for 循环相同。如果测试通过,将执行 if 语句后面所有缩进的代码行,否则将忽略。

    if conditional_test:     #conditional_test:可包含任何条件测试
        do something       #条件为True,执行此代码块;条件为False,不执行此代码块
    例如:
    age = 19
    if age >= 18:
       print("You are old enough to vote!")
    #输出结果:
    You are old enough to vote!

    2. if-else 语句:条件测试通过执行一个操作,没有通过执行另一个操作。

    age = 17
    if age >= 18:              # 条件不通过,执行else的语句块
        print("You are old enough to vote!")
        print("Have you registered to vote yet?")
    else:
        print("Sorry, you are too young to vate.")
        print("Please register to vote as soon as you turn 18!")
    #输出结果:
    Sorry, you are too young to vate.
    Please register to vote as soon as you turn 18!
    

    3. if-elif-else结构:用于超过两个条件的情形。

    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")
    或简易代码如下,此代码中if-elif-else中的作用减弱,但调整价格方面变简易了:
    age = 12
    if age <4:
      price= 0
    elif age < 18:
      price= 5
    else:
      price= 10
    print("You admission cost is $"+ str(price) + ".") #输出结果:Your admission cost is $5

    4. 使用多个elif 代码块

    age = 66
    if age <4:
        price = 0
    elif age < 18:
        price = 5
    elif age <65:
        price = 10
    else:
        price = 5
    print("You admission cost is $"+ str(price) + ".")
    
    #输出结果:You admission cost is $5.
    

    5. 省略else 代码块:部分情况下,使用一条elif 语句处理特定的情形更清晰,所以需要省略 else 代码块。

    age = 66
    if age <4:
        price = 0
    elif age < 18:
        price = 5
    elif age <65:
        price = 10
    elif age >=65:
        price = 5
    print("You admission cost is $"+ str(price) + ".")
    #输出结果:You admission cost is $5.
    

    6. 测试多个条件

    requested_topping = ['mushrooms','extra cheese']
    if 'mushrooms' in requested_topping:
        print("Adding mushrooms")
    if 'pepperoni' in requested_topping:
        print("Adding pepperoni")
    if 'extra cheese' in requested_topping:
        print("Adding extra cheese")
    print("
    Finished making your pizza!")
    
    #输出结果:
    Adding mushrooms
    Adding extra cheese
    
    Finished making your pizza!
    

     解析以上代码:

    a. 创建一个列表,包含顾客点的配料

    b. if 语句检查配料是mushrooms 或 extra cheese 或 pepperoni。这三个if 语句块是独立的测试,就是不会因为前面测试通过而跳出其余的代码块,如果后面的代码块也通过,会继续执行。也就是多重选择,多重结果。

    四、使用if 语句处理列表

    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("Adding" + requested_topping + ".")
    print("
    Finished making your pizza!")
    
    #输出结果:
    Addingmushrooms.
    Sorry, we are out of green peppers right now.
    Addingextra cheese.
    
    Finished making your pizza!
    

     解析以上代码:

    a. 创建一个列表,包含三种配料

    b. for循环语句来依次添加列表中的配料。先检查顾客点的是否是green peppers,如果是,就打印一条消息告知不能点green peppers。else代码块确保其他配料都添加到披萨中。

    c. 添加完成之后,打印一条消息告知顾客配料已经添加完成

    2. 确定列表不是空的

    requested_toppings = []
    if requested_toppings:
        for requested_topping in requested_toppings:
            print("Adding" + requested_topping + ".")
        print("
    Finished making your pizza")
    else:
        print("Are you sure you want a plain pizza?")
    
    #输出结果:
    Are you sure you want a plain pizza?
    

     解析以上代码

    a. 创建一个空列表

    b. 用if 进行检查,如果变量在列表中,执行if 后面的 for 循环语句依次进行配料的添加

    c 用if 进行检查,如果变量不在列表中,就打印询问顾客是否要点不加任何配料的披萨

    3. 使用多个列表

    available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
    requested_toppings = ['mushrooms','frenche 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("
    Finished making your pizza!")
    
    #输出结果:
    Addingmushrooms.
    Sorry, we don't havefrenche fries.
    Addingextra cheese.
    
    Finished making your pizza!
    

     解析以上代码:

    a. 先定义两个列表,第一个列表包含披萨店供应的配料,第二个列表包含顾客点的配料

    b. 用for 循环遍历顾客点的配料列表:检查配料是否包含在供应的配料列表中

    c. 用 if 判断如果顾客要求的配料在供应配料列表中,就执行if 后面的代码块

    d. 用 if 判断如果顾客要求的配料不在供应配料列表中,就执行 else 后面的代码块

    e. 添加完成之后,最后打印告知用户披萨已经完成

    五、设置 if 语句的格式:在==、>=和 <=等比较运算符两边各添加一个空格,代码阅读就更简易。

    备注:内容摘录自《python编程:从入门到实践》

  • 相关阅读:
    C#集合类型——Array、ArrayList、List 之浅谈
    C#反射(二)
    ASP.Net内置对象之网页之间传参(二)
    ASP.Net内置对象之网页之间传参(一)
    MyEclipse中设置智能提示
    常用Java片段
    ue中替换行
    正确的计算耗时
    JAVA之GUI编程ACTION事件
    JAVA之GUI编程窗体事件
  • 原文地址:https://www.cnblogs.com/heiqiuxixi/p/12327168.html
Copyright © 2011-2022 走看看