Python编程:从入门到实践读书笔记-5 if语句 & 6 字典

来源:互联网 发布:js女装是什么牌子档次 编辑:程序博客网 时间:2024/05/16 11:18
自己还是太年轻,昨天受了点刺激就没有坚持学习,不好,得改!
今天周六,一天都泡在西工大自习室,学习的效率很高,不错,得坚持!


5.3.4 使用多个elif代码块
     eg:
          age = 28
          if age < 4:
              price = 0
          elif age < 18:
              price = 5
          elif age < 65:
              price = 10
          else:
              price = 10
          print("Your cost is " + str(price))
     op:
          Your cost is 10
5.3.5 省略else代码块(else非必须有)
     eg:
          age = 68
          if age < 4:
               price = 0
          elif age < 18:
               price = 5
          elif age < 65:
               price = 10
          elif age >= 65:
               price = 5
          print("Your cost is " + str(price)  #没有else
     op:
          Your cost is 5
5.3.6 测试多个条件
     if-elif-else结构功能强大,但仅仅适用于只有一个条件满足的情况,只执行一个代码块的情况;
     但现实是会存在多个条件,运行多个代码块的情况:
     eg:
          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!")
     op:
          Adding mushrooms
          Adding extra cheese

          Finished making your pizza!
     解释:首先,创建了一个包含可点配料的列表,然后检查顾客都点了什么配料,如果
               配料咋列表中,就打印一条确认消息。不论前面条件是否通过测试,都会执行接下来的代码块。
     总结:如果只想执行一个代码块,使用if-elif-else结构;
               如果要运行多个代码块,需使用一系列独立的if语句。
5.4 使用if语句处理列表
     5.4.1 检查特殊元素
     情景1:配料菜单里有3中配菜,顾客每添加一种配料时,打印输出一个消息,最终输出正在完成pisa制作,请稍等片刻。
          eg:
               requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
               for requested_topping in requested_toppings:
                    print("Adding " + requested_topping +".")
               print("\nFinished making your pisa, please wait for a moment!")
          op:
               Adding mushrooms.
               Adding green peppers.
               Adding extra cheese.

               Finished making your pisa, please wait for a moment!
     情景2:顾客点到青椒green peppers时,打印输出提示青椒没有了,请更换别的配料,
                最终输出正在完成pisa制作,请稍等片刻。
          eg:
               requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
               for requested_topping in requested_toppings:
                    if requested_topping == 'green peppers':
                        print("I'm sorry," + requested_topping +"is over, please change it to another")
                    else:
                        print("Adding " + requested_topping +".")
               print("\nFinished making your pisa, please wait for a moment!")
          op:
               Adding mushrooms.
               I'm sorry,green peppersis over, please change it to another
               Adding extra cheese.

               Finished making your pisa, please wait for a moment!
     注意:此例同时使用for循环和if语句
     5.4.2 确定列表不为空
     情景3:制作pisa前检查顾客所点配料单是否为空,如果为空,输出打印确认是否点普通披萨
     eg:
          requested_toppings = []
          if requested_toppings:
              for requested_topping in requested_toppings:
                  print("Adding " + requested_topping + ".")
                  print("\nFinished making your pisa, please wait for a moment!")
          else:
              print("Are you sure you want a plain pizza?")
     注意:if语句中将列表名用在条件表达式中时,列表 至少包含一个元素时返回True列表为空时返回False
     5.4.3 使用多个列表
      情景4:现实中,制作pisa可用配料与顾客实际所需配料不是完全匹配的,顾客所需和可用不一样时,
                 输出打印一条消息,告知可用配料没有XXX
      eg:  
           available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese']
           requested_toppings = ['mushrooms', 'apple', 'green peppers','banana', 'pineapple']
           for requested_topping in requested_toppings:
                if requested_topping in available_toppings:
                   print("Adding " + requested_topping + ".")
               else:
                   print("I'm sorry, we don't have " + requested_topping)
           print("\nFinished making your pisa, please wait for a moment!")      
     op:
          Adding mushrooms.
          I'm sorry, we don't have apple
          Adding green peppers.
          I'm sorry, we don't have banana
          Adding pineapple.

          Finished making your pisa, please wait for a moment!
     疑问:事实上,我想输出adding所有的配料后,再输出we don't have XXX,暂时做不到,待以后回来搞定!
    
     动手试一试
     5-8:
          usernames = ['rose','chandler','admin','joey','monica']
          for username in usernames:
               if username == 'admin':
                    print("Hello " + username.upper() + " would you like to see a status report?")
               else:
                    print("Hello " + username.upper() + " Welcome to Python World!") 
     5-9 
          usernames = ['rose','chandler','admin','joey','monica']
          if usernames:
              for username in usernames:
                  if username == 'admin':
                      print("Hello " + username.title() + " would you like to see a status report?")
                  else:
                      print("Hello " + username.title() + " Welcome to Python World!")
          else:
              print("We need to find some users!")
     5-10:
          current_users = ['rose','chandler','Joey','monica','phebe']
          new_users = ['Rose','chandler','joey','buffy','mike']
          for new_user in new_users:
               if new_user.lower() in current_users.lower():
                    print(new_user + " has been used ,Please change another name !")
               else:
                    print("Good luck, " + new_user + " is available")
          比较时,不区分大小写没做出来。
     5-11:
          numbers = [1,2,3,4,5,6,7,8,9]
          for number in numbers:
              if number == 1:
                   print(str(number) + "st")
              elif number == 2:
                   print(str(number) + "nd")
              elif number == 3:
                  print(str(number) + "rd")
              else:
                  print(str(number) + "th")

遗漏问题:
        5-10不区分大小写没有做出来!!!

6.1 一个简单的字典
     eg:
          alien_0 = {'color':'green','point':5}
          print(alien_0['color'])
          print(alien_0['point'])
     op:
          green
          5
     注意:字典外是大括号;
               字典内有分号:
               打印时要有字典名和键(即输入在方括号内部)
6.2 使用字典(一系列键-值对 )
     字典——一系列键-值对,每个键都与一个值关联,可使用键来访问相关联的值
                    与键相关联的,可以是数字字符串列表乃至字典  
     上例中,键为:color  关联的值:green
                           point  关联的值: 5
       
6.2.1 访问字典中的值(指定字典名+方括号值)    
     要获取与键关联的值,需指定字典名和放在方括号[]内部的键,
     eg:
          alien_0 = {'color':'green','point':5}
          print(alien_0['color'])
     op:
          green
     解释:字典名——alien_0
                     键——color
        键关联的值——green
     字典中可包含任意数量键—值对

6.2.2 添加键-值对
     字典是一种动态结构,即其可随时添加键-值对。
     添加键-值对,需依次指定字典名、方括号括起的键和相关联的值。
     eg:
          alien_0 = {'color':'green','point':5}
          print(alien_0)
          alien_0['x_position'] = 0          #添加时指定字典名alien_0,接下
          alien_0['y_position'] = 25        #指定要添加的键及相关联的值
          print(alien_0)
     op:
          {'color': 'green', 'point': 5}
          {'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}
     注意:键—值对的排列顺序与添加顺序不同
               即python只关心键和值的关联关系,不关心其在字典中排列顺序。

6.2.3 先创建一个空字典
     先使用一对空的花括号定义一个字典,再分别添加各键-值对。
     eg:
          alien_0 = {}
          alien_0['color'] = 'green'
          alien_0['points'] = 5
          print(alien_0)
     op:
          {'color': 'green', 'points': 5}
     注意:使用字典来存储用户提供的数据或在编写能自动生成大量键—值对的代码时,
               通常都需要先 定义一个空字典。

6.2.4 修改字典中的值
     修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值。
     eg:
          alien_0 = {'color':'green','point':5}
          alien_0['color'] = 'yello'
          print(alien_0)
     op:
          {'color': 'yello', 'point': 5}
     情景1:追踪一个以不同速度运动的外星人位置
     eg:
          alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
          print("Original x_position: " + str(alien_0['x_position']))          #定义一个外星人并打印x_position初始位置
          if alien_0['speed'] == 'slow':
              x_increment = 1                                                                 
          elif alien_0['speed'] == 'medium':
              x_increment = 2
          else:
              x_increment = 3                                                               #根据外星人的速度,设置x的增量                 
          alien_0['x_position'] = alien_0['x_position'] + x_increment      #计算x_position最新位置
          print("New x-position: " + str(alien_0['x_position']))
     op:
          Original x_position: 0
          New x-position: 2                                                                 #输出打印结果
     思考:可否将字典理解为对象,键理解为属性,值理解为属性值???
               从节6.2.6看,可以将其理解为对象,属性-属性值
     注意:此例通过修改字典中的值来改变外星人的行为

6.2.5 删除键-值对(del语句)
     对于字典中不再需要的信息,可使用del语句彻底删除。
     使用del语句时, 必须指定字典名和要删除的键。
     eg:
          alien_0 = {'color':'green','point':5}
          print(alien_0)
          del alien_0['color']
          print(alien_0)
     op:
          {'color': 'green', 'point': 5}
          {'point': 5}
     注意:删除的键-值对永远消失了。

6.2.6 由类似对象组成的字典
     从6.2.4可以看出,字典存储的是一个对象(游戏中的一个外星人)的多种信息。
     但是,也可以 使用字典来存储众多对象的同一种信息。
     eg:
         vorite_languages = {
               'jen': 'python',
               'sarah': 'c',
               'edward': 'ruby',
               'phil': 'python',
               }
           print(favorite_languages)
           print("jen's favourate language is " +
                favorite_languages['jen'].title())
     op:     
          {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
          jen's favourate language is Python
     注意:1. 当字典较大时,输入字典名称及左中括号时,回车下一行后开始输入键-值对;
               2. 每行前缩进4个空格,输入的键值对必须要有逗号,
               3. 在最后一个键-值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐
               4. print输出较长时,可按回车键进入print语句的后续各行,并使 用Tab键将它们对齐并缩进一级。
                  指定要打印的所有内容后,在print语句的最后一行末尾加上右括号。

     练习:
     6.1 
          man_name = {
               'first_ name': 'chandler',
               'last_name': 'bing',
               'age': 29,
               'city': 'newyork'
               }
          print(man_name)
     6.2
          favorite_number = {
               'rose': 7,
               'chandler': 8,
               'joey': 9,
               'monica': 2,
               'phebe': 3
               }
          print("rose's favorite number is " + str(favorite_number['rose'])) 
     6.3 
          PLM_word = {
               'program': 'a collection of project',
               'project': 'numbers of task',
               'WBS':'detail schedule of project',
               'issue': 'problem of roject'
               }
          print("program: " + PLM_word['program'])

     
         

     
         





0 0