Chapter 4: Functions | Python for Everybody 讲义笔记_En

news2024/9/26 3:21:31

文章目录

  • Python for Everybody
    • 课程简介
    • Functions
      • Function calls
      • Built-in functions
      • Type conversion functions
      • Math functions
      • Random numbers
      • Adding new functions
      • Definitions and uses
      • Flow of execution
      • Parameters and arguments
      • Fruitful functions and void functions
      • Why functions?
      • Debugging
      • Glossary


Python for Everybody


课程简介

Python for Everybody 零基础程序设计(Python 入门)

  • This course aims to teach everyone the basics of programming computers using Python. 本课程旨在向所有人传授使用 Python 进行计算机编程的基础知识。
  • We cover the basics of how one constructs a program from a series of simple instructions in Python. 我们介绍了如何通过 Python 中的一系列简单指令构建程序的基础知识。
  • The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. 该课程没有任何先决条件,除了最简单的数学之外,避免了所有内容。任何具有中等计算机经验的人都应该能够掌握本课程中的材料。
  • This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. 本课程将涵盖《Python for Everyday》教科书的第 1-5 章。学生完成本课程后,他们将准备好学习更高级的编程课程。
  • This course covers Python 3.

在这里插入图片描述

coursera

Python for Everybody 零基础程序设计(Python 入门)

Charles Russell Severance
Clinical Professor

在这里插入图片描述

个人主页
Twitter

在这里插入图片描述

University of Michigan


课程资源

coursera原版课程视频
coursera原版视频-中英文精校字幕-B站
Dr. Chuck官方翻录版视频-机器翻译字幕-B站

PY4E-课程配套练习
Dr. Chuck Online - 系列课程开源官网


Functions

Take a brief look at how Python implements the ‘store and use later’ programming pattern.


Function calls

In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name. We have already seen one example of a function call:

>>> type(32)
<class 'int'>

The name of the function is type. The expression in parentheses is called the argument of the function. The argument is a value or variable that we are passing into the function as input to the function. The result, for the type function, is the type of the argument.

It is common to say that a function “takes” an argument and “returns” a result. The result is called the return value.

Built-in functions

Python provides a number of important built-in functions that we can use without needing to provide the function definition. The creators of Python wrote a set of functions to solve common problems and included them in Python for us to use.

The max and min functions give us the largest and smallest values in a list, respectively:

>>> max('Hello world')
'w'
>>> min('Hello world')
' '
>>>

The max function tells us the “largest character” in the string (which turns out to be the letter “w”) and the min function shows us the smallest character (which turns out to be a space).

Another very common built-in function is the len function which tells us how many items are in its argument. If the argument to len is a string, it returns the number of characters in the string.

>>> len('Hello world')
11
>>>

These functions are not limited to looking at strings. They can operate on any set of values, as we will see in later chapters.

You should treat the names of built-in functions as reserved words (i.e., avoid using “max” as a variable name).

Type conversion functions

Python also provides built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:

>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'

int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:

>>> int(3.99999)
3
>>> int(-2.3)
-2

float converts integers and strings to floating-point numbers:

>>> float(32)
32.0
>>> float('3.14159')
3.14159

Finally, str converts its argument to a string:

>>> str(32)
'32'
>>> str(3.14159)
'3.14159'

Math functions

Python has a math module that provides most of the familiar mathematical functions. Before we can use the module, we have to import it:

>>> import math

This statement creates a module object named math. If you print the module object, you get some information about it:

>>> print(math)
<module 'math' (built-in)>

The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.

>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)

>>> radians = 0.7
>>> height = math.sin(radians)

The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module also provides a function called log that computes logarithms base e.

The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2 π 2π 2π:

>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.7071067811865476

The expression math.pi gets the variable pi from the math module. The value of this variable is an approximation of π, accurate to about 15 digits.

If you know your trigonometry, you can check the previous result by comparing it to the square root of two divided by two:

>>> math.sqrt(2) / 2.0
0.7071067811865476

Random numbers

Given the same inputs, most computer programs generate the same outputs every time, so they are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious example, but there are more.
Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers. Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from random.

The random module provides functions that generate pseudorandom numbers (which I will simply call “random” from here on).

The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you call random, you get the next number in a long series. To see a sample, run this loop:

import random

for i in range(10):
    x = random.random()
    print(x)

This program produces the following list of 10 random numbers between 0.0 and up to but not including 1.0.

0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867

Exercise 1: Run the program on your system and see what numbers you get. Run the program more than once and see what numbers you get.

The random function is only one of many functions that handle random numbers. The function randint takes the parameters low and high, and returns an integer between low and high (including both).

>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9

To choose an element from a sequence at random, you can use choice:

>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3

The random module also provides functions to generate random values from continuous distributions including Gaussian, exponential, gamma, and a few more.

Adding new functions

So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that execute when the function is called. Once we define a function, we can reuse the function over and over throughout our program.

Here is an example:

def print_lyrics():
    print("I'm a lumberjack, and I'm okay.")
    print('I sleep all night and I work all day.')

def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.

The empty parentheses after the name indicate that this function doesn’t take any arguments. Later we will build functions that take arguments as their inputs.

The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces. The body can contain any number of statements.

If you type a function definition in interactive mode, the interpreter prints ellipses (…) to let you know that the definition isn’t complete:

>>> def print_lyrics():
...     print("I'm a lumberjack, and I'm okay.")
...     print('I sleep all night and I work all day.')
...

To end the function, you have to enter an empty line (this is not necessary in a script).

Defining a function creates a variable with the same name.

>>> print(print_lyrics)
<function print_lyrics at 0xb7e99e9c>
>>> print(type(print_lyrics))
<class 'function'>

The value of print_lyrics is a function object, which has type “function”.

The syntax for calling the new function is the same as for built-in functions:

>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.

Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeat_lyrics:

def repeat_lyrics():
    print_lyrics()
    print_lyrics()

And then call repeat_lyrics:

>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.

But that’s not really how the song goes.

Definitions and uses

Pulling together the code fragments from the previous section, the whole program looks like this:

def print_lyrics():
    print("I'm a lumberjack, and I'm okay.")
    print('I sleep all night and I work all day.')


def repeat_lyrics():
    print_lyrics()
    print_lyrics()

repeat_lyrics()

# Code: http://www.py4e.com/code3/lyrics.py

This program contains two function definitions: print_lyrics and repeat_lyrics. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output.

As you might expect, you have to create a function before you can execute it. In other words, the function definition has to be executed before the first time it is called.

Exercise 2: Move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.

Exercise 3: Move the function call back to the bottom and move the definition of print_lyrics after the definition of repeat_lyrics. What happens when you run this program?

Flow of execution

In order to ensure that a function is defined before its first use, you have to know the order in which statements are executed, which is called the flow of execution.

Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.

Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.

A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off.

That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to execute the statements in another function. But while executing that new function, the program might have to execute yet another function!

Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates.

What’s the moral of this sordid tale? When you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.

Parameters and arguments

Some of the built-in functions we have seen require arguments. For example, when you call math.sin you pass a number as an argument. Some functions take more than one argument: math.pow takes two, the base and the exponent.

Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument:

def print_twice(bruce):
    print(bruce)
    print(bruce)

This function assigns the argument to a parameter named bruce. When the function is called, it prints the value of the parameter (whatever it is) twice.

This function works with any value that can be printed.

>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> import math
>>> print_twice(math.pi)
3.141592653589793
3.141592653589793

The same rules of composition that apply to built-in functions also apply to user-defined functions, so we can use any kind of expression as an argument for print_twice:

>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0

The argument is evaluated before the function is called, so in the examples the expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once.

You can also use a variable as an argument:

>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.

The name of the variable we pass as an argument (michael) has nothing to do with the name of the parameter (bruce). It doesn’t matter what the value was called back home (in the caller); here in print_twice, we call everybody bruce.

Fruitful functions and void functions

Some of the functions we are using, such as the math functions, yield results; for lack of a better name, I call them fruitful functions. Other functions, like print_twice, perform an action but don’t return a value. They are called void functions.

When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:

x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2

When you call a function in interactive mode, Python displays the result:

>>> math.sqrt(5)
2.23606797749979

But in a script, if you call a fruitful function and do not store the result of the function in a variable, the return value vanishes into the mist!

math.sqrt(5)

This script computes the square root of 5, but since it doesn’t store the result in a variable or display the result, it is not very useful.

Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None.

>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None

The value None is not the same as the string “None”. It is a special value that has its own type:

>>> print(type(None))
<class 'NoneType'>

To return a result from a function, we use the return statement in our function. For example, we could make a very simple function called addtwo that adds two numbers together and returns a result.

def addtwo(a, b):
    added = a + b
    return added

x = addtwo(3, 5)
print(x)

# Code: http://www.py4e.com/code3/addtwo.py

When this script executes, the print statement will print out “8” because the addtwo function was called with 3 and 5 as arguments. Within the function, the parameters a and b were 3 and 5 respectively. The function computed the sum of the two numbers and placed it in the local function variable named added. Then it used the return statement to send the computed value back to the calling code as the function result, which was assigned to the variable x and printed out.

Why functions?

It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:

  • Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read, understand, and debug.

  • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.

  • Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.

  • Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.

Throughout the rest of the book, often we will use a function definition to explain a concept. Part of the skill of creating and using functions is to have a function properly capture an idea such as “find the smallest value in a list of values”. Later we will show you code that finds the smallest in a list of values and we will present it to you as a function named min which takes a list of values as its argument and returns the smallest value in the list.

Debugging

If you are using a text editor to write your scripts, you might run into problems with spaces and tabs. The best way to avoid these problems is to use spaces exclusively (no tabs). Most text editors that know about Python do this by default, but some don’t.

Tabs and spaces are usually invisible, which makes them hard to debug, so try to find an editor that manages indentation for you.

Also, don’t forget to save your program before you run it. Some development environments do this automatically, but some don’t. In that case, the program you are looking at in the text editor is not the same as the program you are running.

Debugging can take a long time if you keep running the same incorrect program over and over!

Make sure that the code you are looking at is the code you are running. If you’re not sure, put something like print("hello") at the beginning of the program and run it again. If you don’t see hello, you’re not running the right program!

Glossary

algorithm
A general process for solving a category of problems.
argument
A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
body
The sequence of statements inside a function definition.
composition
Using an expression as part of a larger expression, or a statement as part of a larger statement.
deterministic
Pertaining to a program that does the same thing each time it runs, given the same inputs.
dot notation
The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.
flow of execution
The order in which statements are executed during a program run.
fruitful function
A function that returns a value.
function
A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.
function call
A statement that executes a function. It consists of the function name followed by an argument list.
function definition
A statement that creates a new function, specifying its name, parameters, and the statements it executes.
function object
A value created by a function definition. The name of the function is a variable that refers to a function object.
header
The first line of a function definition.
import statement
A statement that reads a module file and creates a module object.
module object
A value created by an import statement that provides access to the data and code defined in a module.
parameter
A name used inside a function to refer to the value passed as an argument.
pseudorandom
Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.
return value
The result of a function. If a function call is used as an expression, the return value is the value of the expression.
void function
A function that does not return a value.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/731352.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

GEE:GEE上一些好看的可视化参数

作者&#xff1a;CSDN _养乐多_ 为了方便使用&#xff0c;总结了几种可视化参数。 文章目录 一、连续型1.11.21.31.41.5 二、离散型2.1 一、连续型 1.1 var phenoPalette [ff0000,ff8d00,fbff00,4aff00,00ffe7,01b8ff,0036ff,fb00ff]1.2 var evapotranspirationVis {min…

异地手机卡如何在当地办理宽带【纯教程篇】

有一些小伙伴常年在外漂泊会经常使用异地卡套餐&#xff0c;但是当你需要办理宽带业务的时候&#xff0c;很多时候当地的营业厅会让你再办理一张他们本地的手机卡&#xff0c;不方便不说还要多支付一张卡的月租也不划算。 其实呢运营商早就有异地办理宽带的业务&#xff0c;只不…

公司新来了个卷王,还是个00后,我们这帮老油条真干不过...

都说00后躺平了&#xff0c;但是有一说一&#xff0c;该卷的还是卷。这不&#xff0c;前段时间我们公司来了个00后&#xff0c;工作没两年&#xff0c;跳槽到我们公司起薪18K&#xff0c;都快接近我了。后来才知道人家是个卷王&#xff0c;从早干到晚就差搬张床到工位睡觉了。 …

浅析集群、分布式、负载均衡

平时开发或者面试中进场听到集群、分布式、负载均衡等系列的名词&#xff0c;他们之间有什么联系呢&#xff0c;本文就简要的抛砖引玉一下。 集群 1.什么是集群 集群一般指的是服务器集群。集群其实就是一组相互独立的计算机&#xff0c;通过高速的网络组成一个计算机系统。…

深度学习笔记之Transformer(六)Position Embedding铺垫:Skipgram与CBOW模型

深度学习笔记之Transformer——PositionEmbedding铺垫&#xff1a;Skipgram与CBOW模型 引言回顾&#xff1a; Word2vec \text{Word2vec} Word2vec模型补充&#xff1a;关于 Word2vec \text{Word2vec} Word2vec的一些说明 引言 上一节介绍了 Word2vec \text{Word2vec} Word2vec…

【动态规划算法】第九题:64. 最小路径和

&#x1f496;作者&#xff1a;小树苗渴望变成参天大树&#x1f388; &#x1f389;作者宣言&#xff1a;认真写好每一篇博客&#x1f4a4; &#x1f38a;作者gitee:gitee✨ &#x1f49e;作者专栏&#xff1a;C语言,数据结构初阶,Linux,C 动态规划算法&#x1f384; 如 果 你…

Todo-List案例版本一

初级使用e.target.value 记得安装npm i nanoid与UUID类似 快捷键ctrlH替换内容 src/components/MyHeader.vue <template><div class"todo-header"><input type"text" placeholder"请输入你的任务名称&#xff0c;按回车键确认&quo…

express框架中使用ejs

1.设置模块引擎为ejs app.set("view engine","ejs") 2. 设置模版文件存放位置 说明&#xff1a;模版文件&#xff1a;具有模版语法内容的文件。 app.set(vies,path.resolve(__dirname,"./views")) 3.render渲染 app.get(/home,(req,res)>{/…

MySQL第三天(简单单表查询)

前言 今天的三个题目是针对于单表查询和多表查询的课后作业&#xff0c;针对于初学者还是很合适的听有用处的&#xff0c;我会把我的答题过程一步一步写出来&#xff0c;有需要的小伙伴可以参考哦… 第一题、单表信息查询 题目代码如下&#xff1a; 作业&#xff1a;1.创建表…

【计算机组成原理总结】

第一章计算机系统概述 第二章数据的表示与运算 第三章存储系统 第四章 指令系统 第五章 中央处理器 第六章 总线 第七章 输入输出设备

Mac如何在终端使用diskutil命令装载和卸载推出外接硬盘

最近用 macOS 装载外接硬盘的时候&#xff0c;使用mount死活装不上&#xff0c;很多文章也没详细的讲各种情况&#xff0c;所以就写一篇博客来记录一下。 如何装载和卸载硬盘&#xff08;或者说分区&#xff09; mount和umount是在 macOS 上是不能用的&#xff0c;如果使用会…

Clickhouse入门(一)

第一章 Clickhouse简介 ClickHouse (C编写)是俄罗斯的Yandex(相当于百度)于2016年开源的列式存储数据库&#xff08;DBMS&#xff09;&#xff0c;使用C语言编写&#xff0c;主要用于在线分析处理查询&#xff08;OLAP&#xff09;&#xff0c;能够使用SQL查询实时生成分析数据…

电脑各配置跟不上,造成频繁花屏。

本人用的是i3 7350K&#xff0c;然而散热器是二十多块的杂牌&#xff0c;CPU温度经常不稳定&#xff0c;可以在监控软件看到比较详细的情况&#xff0c;然后我的显卡是gtx1080&#xff0c;内存加到双条24G。 最近一直花屏&#xff0c;我甚至怀疑是不是显卡坏了&#xff0c;然后…

特征选择算法 | Matlab 基于最大互信息系数特征选择算法(MIC)的回归数据特征选择

文章目录 效果一览文章概述部分源码参考资料效果一览 文章概述 特征选择算法 | Matlab 基于最大互信息系数特征选择算法(MIC)的回归数据特征选择 部分源码 %--------------------

css 字体间距 设置

一、css word-spacing属性设置字间距&#xff08;单词的间距&#xff09; word-spacing 属性增加或减少单词间的空白&#xff08;即字间隔&#xff09;&#xff1b;在这个属性中&#xff0c;“字” 定义为由空白符包围的一个字符串。也就是说该属性是以空格为基准进行调节间距…

【一】PCIe基础知识

一、PCIe概述 1、PCIe速度 PCI采用总线共享式通讯方式&#xff1b;PCIe采用点到点(Endpoint to Endpoint)通讯方式&#xff0c;互为接收端和发送端&#xff0c;全双工&#xff0c;基于数据包传输&#xff1b;两个PCIe设备之间的连接称作一条链路(link)&#xff0c; 一条链路可…

Nginx报跨域问题怎么解决

这就是报错信息&#xff0c;可以看出这里是一个请求发送了两次&#xff0c;这是什么原因呢&#xff1f; 这种请求是因为它是applocayion/json格式的请求&#xff0c;在请求一个资源的时候&#xff0c;先会发送一个预检请求&#xff0c;然后才会发送真正的请求&#xff0c;那为…

桥接模式:如何实现支持不同类型和渠道的消息推送系统?

上一节课我们学习了第一种结构型模式&#xff1a;代理模式。它在不改变原始类&#xff08;或者叫被代理类&#xff09;代码的情况下&#xff0c;通过引入代理类来给原始类附加功能。代理模式在平时的开发经常被用到&#xff0c;常用在业务系统中开发一些非功能性需求&#xff0…

Web前端 Day 2

元素显示模式 块元素 独占一行 宽、高、内外边距可以设置 eg. div 行内元素 一行可以存在多个 eg. span 行内块元素 一行可以存在多个 宽、高、内外边距可以设置 是否独占一行 表格标签 <table> <caption></caption> 表格标题&#xff08;概括&#…

手把手的教你安装PyCharm --Pycharm安装详细教程(一)(非常详细,非常实用)

简介 Jetbrains家族和Pycharm版本划分&#xff1a; pycharm是Jetbrains家族中的一个明星产品&#xff0c;Jetbrains开发了许多好用的编辑器&#xff0c;包括Java编辑器&#xff08;IntelliJ IDEA&#xff09;、JavaScript编辑器&#xff08;WebStorm&#xff09;、PHP编辑器&…