百度飞桨领航团零基础Python速成营 课程总结3

百度飞桨领航团零基础Python速成营 课程总结3

  • 课节3: Python函数基础
    • 函数(Function)
    • 模块(Module)
    • 作业三:Python函数基础(大作业)

 
课程链接:https://aistudio.baidu.com/aistudio/course/introduce/7073
飞桨官网:https://www.paddlepaddle.org.cn/
推荐学习网站:https://www.runoob.com/python3/python3-tutorial.html
 

课节3: Python函数基础

函数(Function)

  • 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
  • 函数能提高应用的模块性,和代码的重复利用率。
  • 定义函数
    def functionname( parameters ): 
    	"函数_文档字符串" 
    	function_suite 
    	return [expression]
    
  • 参数传递:
    • 必选参数:必选参数须以正确的顺序传入函数、数量必须和声明时的一样。
    • 默认参数:默认参数的值如果没有传入,则被认为是默认值。
    • 可变参数:加了星号(*)的变量名会存放所有未命名的变量参数。可变参数在函数调用时自动组装为一个tuple。
    • 关键字参数:关键字参数在函数内部自动组装为一个dict。
      def score_info(name, **kw):
          if '语文成绩' in kw:
              print(name, '的语文成绩', kw['语文成绩'])
          if '数学成绩' in kw:
              print(name, '的数学成绩', kw['数学成绩'])
              
      
      def person_info(name, age, **kw):
          print('姓名:', name, ' 年龄',age)
          score_info(name, **kw)    
      
      score_cfg = {
               '语文成绩':65, '数学成绩':60}
      person_info('张三', 18, **score_cfg)
      
    • 命名关键字参数:限制关键字参数的名字。和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,后面的参数被视为命名关键字参数。 命名关键字参数必须传入参数名,可以有缺省值,可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔 符
    • 参数定义的顺序必须是:必选参数 --> 默认参数 --> 可变参数 --> 命名关键字参数 --> 关键字参数
  • 命名空间(Namespace):
    命名空间是从名称到对象的映射,大部分的命名空间都是通过 Python 字典来实现的。命名空间提供了在项目中避免名字冲突的一种方法。各个命名空间是独立的,没有任何关系的,所以一个命名空间中不能有重名,但不同的命名空间是可以重名而没有任何影响。
    • 内置命名空间(Built-in names): 用于存放Python 的内置函数的空间,比如,print,input等不需要定义即可使用的函数就处在内置命名空间。
    • 全局命名空间(Global names):模块中定义的名称,记录了模块的变量,包括函数、类、其它导入的模块、模块级的变量和常量。
    • 局部命名空间(Local names):函数中定义的名称,记录了函数的变量,包括函数的参数和局部定义的变量。在函数内定义的局部变量,在函数执行结束后就会失效,即无法在函数外直接调用函数内定义的变量。
    • 命名空间查找顺序: 局部命名空间→全局命名空间→内置命名空间。
    • 命名空间的生命周期:取决于对象的作用域,如果对象执行完成,则该命名空间的生命周期就结束。
  • 作用域(Scope):
    作用域就是一个 Python 程序可以直接访问命名空间的正文区域。在一个 python 程序中,直接访问一个变量,会从内到外依次访问所有的作用域直到找到,否则会报未定义的错误。
    • Local:在程序的最内层,包含局部变量,比如,一个函数的内部。
    • Enclosing:包含了非局部(non-local)也非全局(non-global)的变量。比如,两个嵌套函数,函数(或类)A里面又包含了函数B,那么对于B中的名称来说 A中的作用域就为no-nlocal。
    • Global:当前脚本的最外层,比如,当前模块的全局变量。
    • Built-in: 包含了内建的变量/关键字等,比如,int。全局变量和局部变量。定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
    • 作用域查找顺序: L –> E –> G –> B。
  • 匿名函数:lambda [arg1 [,arg2,…argn]]:expression
  • 高阶函数:一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归)。
    • map() 函数会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
      map(function, iterable, …)。
      Python 2.x 返回列表。Python 3.x 返回迭代器。

    • reduce() 函数会对参数序列中元素进行累积。函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
      reduce(function, iterable[, initializer])

      • 注意:Python3.x reduce() 已经被移到 functools 模块里,如果我们要使用,需要引入 functools 模块来调用 reduce() 函数:from functools import reduce
    • sorted() 函数对所有可迭代的对象进行排序操作。sorted(iterable, cmp=None, key=None, reverse=False)

    • 偏函数:将所要承载的函数作为partial()函数的第一个参数,原函数的各个参数依次作为partial()函数后续的参数,除非使用关键字参数。from functools import partial

    • 装饰器(Decorators):修改其他函数的功能的函数。装饰器最大的优势是用于解决重复性的操作,其主要使用的场景有如下几个:

      • 计算函数运行时间
      • 给函数打日志
      • 类型检查
      	# 装饰器输入一个函数,输出一个函数
      def print_working(func):
          def wrapper():
              print(f'{func.__name__} is working...')
              func()
          return wrapper
      
      def worker1():
          print('我是一个勤劳的工作者!')
      def worker2():
          print('我是一个勤劳的工作者!')
      def worker3():
          print('我是一个勤劳的工作者!')
      
      worker1 = print_working(worker1)
      worker1()
      worker2= print_working(worker2)
      worker2()
      worker3= print_working(worker2)
      worker3()
      
      @print_working
      def worker1():
          print('我是一个勤劳的工作者!')
      
      @print_working
      def worker2():
          print('我是一个勤劳的工作者!')
      
      @print_working
      def worker3():
          print('我是一个勤劳的工作者!')
      worker1()
      worker2()
      worker3()
      
    • 闭包(Closure):一个函数定义中引用了函数外定义的变量,并且该函数可以在其定义环境外被执行。这样的一个函数我们称之为闭包。

      # 一个需要注意的问题是,返回的函数并没有立刻执行,而是直到调用了f()才执行。
      
      def count():
          fs = []
          for i in range(1, 4):
              def f():
                  # print(id(i))
                  return i*i
              fs.append(f)
          return fs
      
      f1, f2, f3 = count()
      print(f1())
      print(f2())
      print(f3())
      

      输出:

      9
      9
      9
      
      def count():
          def f(j):
              def g():
                  # print(id(j))
                  return j*j
              return g
          fs = []
          for i in range(1, 4):
              fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
          return fs
      
      f1, f2, f3 = count()
      print(f1())
      print(f2())
      print(f3())
      

      输出:

      1
      4
      9
      
      • 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。

模块(Module)

  • import 语句:import module1[, module2[,… moduleN]]。调用模块中函数:模块名.函数名。
  • from…import语句:from modname import name1[, name2[, … nameN]]。
    • 一个模块只会被导入一次,不管你执行了多少次import。
  • 安装/卸载:
    • pip install / uninstall
    • conda install / uninstall

 

作业三:Python函数基础(大作业)

作业内容:

  • 统计英语6级试题中所有单词的词频,并返回一个如下样式的字典
    {‘and’:100,‘abandon’:5}

  • 英语6级试题的文件路径./artical.txt

  • Tip: 读取文件的方法

    def get_artical(artical_path):
        with open(artical_path) as fr:
            data = fr.read()
        return data
    
    get_artical('./artical.txt')
    

处理要求:

  • (a) '\n’是换行符 需要删除
  • (b) 标点符号需要处理 [’.’, ‘,’, ‘!’, ‘?’, ‘;’, ‘’’, ‘"’, ‘/’, ‘-’, ‘(’, ‘)’]
  • © 阿拉伯数字需要处理 [‘1’,‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’,‘0’]
  • (d) 注意大小写 一些单词由于在句首,首字母大写了。需要把所有的单词转成小写 ‘String’.lower()
  • (e) 高分项
    通过自己查找资料学习正则表达式,并在代码中使用(re模块)
    可参考资料:https://docs.python.org/3.7/library/re.html
# 请根据处理要求下面区域完成代码的编写。
def get_artical(artical_path):
    with open(artical_path) as fr:
        data = fr.read()
    return data

# get_artical()为自定义函数,可用于读取指定位置的试题内容。
str_artical=get_artical('./artical.txt')
import string
# 去除数字
from string import digits
str_digits = str_artical.translate(str.maketrans('', '', digits))

# 去除符号
from string import punctuation
str_punctuation = str_digits.translate(str.maketrans('', '', punctuation))

# 去除选项中ABCD字母(题目没要求,个人添加)
#str_question = str_punctuation.translate(str.maketrans('', '', 'ABCD'))

# 小写
str_lower=str_question.lower()

# 去除空字符,切片
str_spilt=str_lower.split()

# 打印词频列表
num_words = {
     }
for str_spilt in str_spilt:
     num_words[str_spilt] = num_words.get(str_spilt, 0) + 1
print(num_words)
# 输出词频txt文本文件(题目没要求)
s = str(num_words)
f = open('dict.txt','w')
f.writelines(s)
f.close()
# 词频查询(题目没要求)
str_spilt=str_lower.split()
word=input('输入要查询的单词的次数')
print(str_spilt.count(word))

 

——以下为作业所需article.txt文档内容——

Passage One

Questions 46 to 50 are based on the following passage.

Last year, a child was born at a hospital in the UK with her heart outside her body. Few babies survive this rare condition, and those who do must endure numerous operations and are likely to have complex needs. When her mother was interviewed, three weeks after her daughter’s birth, she was asked if she was prepared for what might be a daunting task caring for her. She answered without hesitation that, as far as she was concerned, this would be a “privilege”.

Rarely has there been a better example of the power of attitude, one of our most powerful psychological tools. Our attitudes allow us to turn mistakes into opportunities, and loss into the chance for new beginnings. An attitude is a settled way of thinking, feeling and/or behaving towards particular objects, people, events or ideologies. We use our attitudes to filter, interpret and react to the world around us. You weren’t born with attitudes, rather they are all learned, and this happens in a number of ways.

The most powerful influences occur during early childhood and include both what happened to you directly, and what those around you did and said in your presence. As you acquire a distinctive identity, your attitudes are further refined by the behavior of those with whom you identify – your family, those of your gender and culture, and the people you admire, even though you may not know them personally. Friendships and other important relationships become increasingly important, particularly during adolescence. About that same time and throughout adulthood, the information you receive, especially when ideas are repeated in association with goals and achievements you find attractive, also refines your attitudes.

Many people assume that our attitudes are internally consistent, that is, the way you think and feel about someone or something predicts your behavior towards them. However, may studies have found that feelings and thoughts don’t necessarily predict behavior. In general, your attitudes will be internally consistent only when the behavior is easy, and when those around you hold similar beliefs. That’s why, for example, may say they believe in the benefits of recycling or exercise, but don’t behave in line with their views, because it takes awareness, effort and courage to go beyond merely stating that you believe something is a good idea.

One of the most effective ways to change an attitude is to start behaving as if you already feel and think the way you’d prefer to. Take some time to reflect on your attitudes, to think about what you believe and why. Is there anything you consider a burden rather than a privilege? It so, start behaving – right now – as if the latter is the case.

  1. What do we learn from the passage about attitude?
    A) It shapes our beliefs and ideologies.
    B) It improves our psychological wellbeing.
    C) It determines how we respond to our immediate environment.
    D) It changes the way we think, feel and interact with one another.
  2. What can contribute to the refinement of one’s attitude, according to the passage?
    A) Their idols’ behaviors.
    B) Their educational level.
    C) Their contact with the opposite gender.
    D) Their interaction with different cultures.
  3. What do many studies find about people’s feelings and thoughts?
    A) They may not suggest how a person is going to behave.
    B) They are in a way consistent with a person’s mentality.
    C) They may not find expression in interpersonal relations.
    D) They are in line with a person’s behavior no matter what.
  4. How come many people don’t do what they believe is good?
    A) They can’t afford the time.
    B) They have no idea how to.
    C) They are hypocritical.
    D) They lack willpower.
  5. What is proposed as a strategy to change attitude?
    A) Changing things that require one’s immediate attention.
    B) Starting to act in a way that embodies one’s aspirations.
    C) Adjusting one 's behavior gradually over a period of time.
    D) Considering ways of reducing one’s psychological burdens.

Passage Two

Questions 51 to 55 are based on the following passage.

Industrial fishing for krill in the unspoilt waters around Antarctica is threatening the future of one of the world’s last great wildernesses, according to a new report.

The study by Greenpeace analysed the movements of krill fishing vessels in the region and found they were increasingly operating “in the immediate vicinity of penguin colonies and whale feeding grounds”. It also highlights incidents of fishing boats being involved in groundings, oil spills and accidents, which posed a serious threat to the Antarctic ecosystem.

The report, published on Tuesday, comes amid growing concern about the impact of fishing. and climate change on the Antarctic. A global campaign has been launched to create a network of ocean sanctuaries to protect the seas in the region and Greenpeace is calling for an immediate halt to fishing in areas being considered for sanctuary status.

Frida Bengtsson from Greenpeace’s Protect the Antarctic campaign said: “If the krill industry wants to show it’s a responsible player, then it should be voluntarily getting out of any area which is being proposed as an ocean sanctuary, and should instead be backing the protection of these huge tracts of the Antarctic.”

A global campaign has been launched to turn a huge tract of Antarctic seas into ocean sanctuaries, protecting wildlife and banning not just krill fishing, but all fishing. One was created in the Ross Sea in 2016, another reserve is being proposed in a vast area of the Weddell Sea, and a third sanctuary is under consideration in the area west of the Antarctic Peninsula – a key krill fishing area.

The Commission for the Conservation of Antarctic Marine Living Resources (CCAMLR) manages the seas around Antarctica. It will decide on the Weddell Sea sanctuary proposal at a conference in Australia in October, although a decision on the peninsula sanctuary is not expected until later.

Keith Reid, a science manager at CCAMLR, said that the organisation sought “a balance between protection, conservation and sustainable fishing in the Southern Ocean.” He said although more fishing was taking place nearer penguin colonies it was often happening later in the season when these colonies were empty.

“The creation of a system of marine protected areas is a key part of ongoing scientific and policy discussions in CCAMLR,” he added. “Our long-term operation in the region depends on a healthy and thriving Antarctic marine ecosystem, which is why we have always had an open dialogue with the environmental non-governmental organisations. We strongly intend to continue this dialogue, including talks with Greenpeace, to discuss improvements based on the latest scientific data. We are not the ones to decide on the establishment of marine protected areas, but we hope to contribute positively with our knowledge and experience.”

  1. What does Greenpeace’s study find about krill fishing?
    A) It caused a great many penguins and whales to migrate.
    B) It was depriving penguins and whales of their habitats.
    C) It was carried out too close to the habitats of penguins and whales.
    D) It posed an unprecedented threat to the wildlife around Antarctica.
  2. For what purpose has a global campaign been launched?
    A) To reduce the impact of climate change on Antarctica.
    B) To establish conservation areas in the Antarctic region.
    C) To regulate krill fishing operations in the Antarctic seas.
    D) To publicise the concern about the impact of krill fishing.
  3. What is Greenpeace’s recommendation to the krill industry?
    A) Opting to operate away from the suggested conservation areas.
    B) Volunteering to protect the endangered species in the Antarctic.
    C) Refraining from krill fishing throughout the breeding season.
    D) Showing its sense of responsibility by leading the global campaign.
  4. What did CCAMLR aim to do according to its science manager?
    A) Raise public awareness of the vulnerability of Antarctic species.
    B) Ban all commercial fishing operations in the Southern Ocean.
    C) Keep the penguin colonies from all fishing interference.
    D) Sustain fishing without damaging the Antarctic ecosystem.
  5. How does CCAMLR define its role in the conservation of the Antarctic environment?
    A) A coordinator in policy discussions.
    B) An authority on big data analysis.
    C) A provider of the needed expertise.
    D) An initiator of marine sanctuaries.

Passage One

Questions 46 to 50 are based on the following passage.

Schools are not just a microcosm of society; they mediate it too. The best seek to alleviate the external pressures on their pupils while equipping them better to understand and handle the world outside – at once sheltering them and broadening their horizons. This is ambitious in any circumstances, and in a divided and unequal society the two ideals can clash outright.

Trips that many adults would consider the adventure of a lifetime – treks in Bomeo, a sports tour to Barbados – appear to have become almost routine at some state schools. Parents are being asked for thousands of pounds. Though schools cannot profit from these trips, the companies that arrange them do. Meanwhile, pupils arrive at school hungry because their families can’t afford breakfast. The Child Poverty Action Group says nine out of 30 in every classroom fall below the poverty line. The discrepancy is startlingly apparent. Introducing a fundraising requirement for students does not help, as better-off children can tap up richer aunts and neighbours.

Probing the rock pools of a local beach or practising French on a language exchange can fire children’s passions, boost their skills and open their eyes to life 's possibilities. Educational outings help bright but disadvantaged students to get better scores in A-level tests. In this globalised age, there is a good case for international travel, and some parents say they can manage the cost of a school trip abroad more easily than a family holiday. Even in the face of immense and mounting financial pressures, some schools have shown remarkable determination and ingenuity in ensuring that all their pupils are able to take up opportunities that may be truly life-changing. They should be applauded. Methods such as whole-school fundraising, with the proceeds pooled, can help to extend opportunities and fuel community spirit.

But 3,000 pounds trips cannot be justified when the average income for families with children is just over 30,000 pounds. Such initiatives close doors for many pupils. Some parents pull their children out of school because of expensive field trips. Even parents who can see that a trip is little more than a party or celebration may well feel guilt that their child is left behind.

The Department for Education 's guidance says schools can charge only for board and lodging if the trip is part of the syllabus, and that students receiving government aid are exempt from these costs. However, many schools seem to ignore the advice; and it does not cover the kind of glamorous, exotic trips, which are becoming increasingly common. Schools cannot be expected to bring together communities single-handed. But the least we should expect is that they do not foster divisions and exclude those who are already disadvantaged.

  1. What does the author say best schools should do?
    A) Prepare students to both challenge and change the divided unequal society.
    B) Protect students from social pressures and enable them to face the world.
    C) Motivate students to develop their physical as well as intellectual abilities.
    D) Encourage students to be ambitious and help them to achieve their goals.
  2. What does the author think about school field trips?
    A) They enable students from different backgrounds to mix with each other.
    B) They widen the gap between privileged and disadvantaged students.
    C) They give the disadvantaged students a chance to see the world.
    D) They only benefit students with rich relatives and neighbours.
  3. What does the author suggest can help build community spirit?
    A) Events aiming to improve community services.
    B) Activities that help to fuel students’ ingenuity.
    C) Events that require mutual understanding,
    D) Activities involving all students on campus.
  4. What do we learn about low-income parents regarding school field trips?
    A) They want their children to participate even though they don’t see much benefit.
    B) They don’t want their kids to participate but find it hard to keep them from going.
    C) They don’t want their kids to miss any chance to broaden their horizons despite the cost.
    D) They want their children to experience adventures but they don’t want them to run risks.
  5. What is the author’s expectation of schools?
    A) Bringing a community together with ingenuity.
    B) Resolving the existing discrepancies in society.
    C) Avoiding creating new gaps among students.
    D) Giving poor students preferential treatment.

Passage Two

Questions 51 to 55 are based on the following passage.

Rising temperatures and overfishing in the pristine waters around the Antarctic could see king penguin populations pushed to the brink of extinction by the end of the century, according to a new study. The study’s report states that as global warming transforms the environment in the world’s last great wilderness, 70 percent of king penguins could either disappear or be forced to find new breeding grounds.

Co-author Celine Le Bohec, from the University of Strasbourg in France, warned: “If there’re no actions aimed at halting or controlling global warming, and the pace of the current human-induced changes such as climate change and overfishing stays the same, the species may soon disappear.” The findings come amid growing concern over the future of the Antarctic. Earlier this month a separate study found that a combination of climate change and industrial fishing is threatening the krill population in Antarctic waters, with a potentially disastrous impact on whales, seals and penguins. But today’s report is the starkest warming yet of the potentially devastating impact of climate change and human exploitation on the Antarctic’s delicate ecosystems.

Le Bohec said: “Unless current greenhouse gas emissions drop, 70 percent of king penguins – 1.1 million breeding pairs – will be forced to relocate their breeding grounds, or face extinction by 2100.” King penguins are the second-largest type of penguin and only breed on specific isolated islands in the Southern Ocean where there is no ice cover and easy access to the sea. As the ocean warms, a body of water called the Antarctic Polar Front – an upward movement of nutrient-rich sea that supports a huge abundance of marine life – is being pushed further south. This means that king penguins, which feed on fish and kill in this body of water, have to travel further to their feeding grounds, leaving their hungry chicks for longer. And as the distance between their breeding, grounds and their fool prows, entire colonies could be wiped out.

Le Bohec said: “The plight of the king penguin should serve as a warming about the future of the entire marine environment in the Antarctic. Penguins, like other seabirds and marine mammals, occupy higher levels in the food chain and they are what we call bio-indicators of their ecosystems.” Penguins are sensitive indicators of changes in marine ecosystems. As such, they are key species for understanding and predicting impacts of global change on Antarctic and sub-Antarctic marine ecosystems. The report found that although some king penguins may be able to relocate to new breeding grounds closer to their retreating food source, suitable new habitats would be scarce. Only a handful of islands in the Southern Ocean are suitable for sustaining large breeding colonies.

  1. What will happen by 2100, according to a new study?
    A) King penguins in the Antarctic will be on the verge of dying out.
    B) Sea water will rise to a much higher level around the Antarctic.
    C) The melting ice cover will destroy the great Antarctic wilderness.
    D) The pristine waters around the Antarctic will disappear forever.
  2. What do we learn from the findings of a separate study?
    A) Shrinking krill population and rising temperatures could force Antarctic whales to migrate.
    B) Human activities have accelerated climate change in the Antarctic region in recent years.
    C) Industrial fishing and climate change could be fatal to certain Antarctic species.
    D) Krill fishing in the Antarctic has worsened the pollution of the pristine waters.
  3. What does the passage say about king penguins?
    A) They will turn out to be the second-largest species of birds to become extinct.
    B) Many of them will have to migrate to isolated islands in the Southern Ocean.
    C) They feed primarily on only a few kinds of krill in the Antarctic Polar Front.
    D) The majority of them may have to find new breeding grounds in the future.
  4. What happens when sea levels rise in the Antarctic?
    A) Many baby king penguins can’t have food in time.
    B) Many king penguins could no longer live on kill.
    C) Whales will invade king penguins’ breeding grounds.
    D) Whales will have to travel long distances to find food.
  5. What do we learn about the Southern Ocean?
    A) The king penguins there are reluctant to leave for new breeding grounds.
    B) Its conservation is key to the sustainable propagation of Antarctic species.
    C) It is most likely to become the ultimate retreat for species like the king penguin.
    D) Only a few of its islands can serve as luge breeding grounds for king penguins.

你可能感兴趣的:(百度飞桨,Python学习笔记,paddle,python)