Think Python:Chapter 3: Functions 的笔记

来源:互联网 发布:vb label 换行 编辑:程序博客网 时间:2024/05/22 14:21

目录

这是麻省理工大学(MIT)官方编程教程中Python Tutorial的内容,教材为《Think Python: How to Think Like a Computer Scientist》。这是我的学习笔记,因为水品有限,请大家多多包涵。如果有一起学习的同学可以一起交流。如笔记中错误,请一定要告诉我啊,我肯定及时改正。所有笔记的目录详见:MIT:Python Tutorial目录

这是MIT官方编程教程中Python TutorialFunctions and Scope的内容。本篇博客为《 Think Python: How to Think Like a Computer Scientist》的第3章 Functions 的笔记内容。(Think Python:Chapter 3: Functions

Python Tutorial:Functions and Scope

READING LIST:

  • Think Python, Chapter 3: Functions
  • Think Python, Chapter 6: Fruitful Functions, sections 1-4
  • 6.01 Python Notes, Section 2: Procedures (PDF)

Think Python, Chapter 3: Functions

3.1 Function calls

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 definition: A statement that creates a new function, specifying its name, parameters, and the statements it executes.

function call: A statement that executes a function. It consists of the function name followed by an argument list.

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.

3.2 Type conversion functions(类型转换函数)

Python provides built-in functions that convert values from one type to another.(for example: int function)

>>> int('32')32>>> int('hello')Traceback (most recent call last):File "<pyshell#14>", line 1, in <module>int('hello')ValueError: invalid literal for int() with base 10: 'hello'>>> int(2.3)2>>> int(-2.3)-2 

3.3 Math functions(数学函数)

Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions.

Before we can use the module, we have to import it (调用模块,用 import ):

>>> import math

This statement creates a module object named math. If you print the module object, you get some information about it (查看模块或函数信息,用 print ):

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

dot notation: 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 (用.调用模块中的函数):

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

3.4 Composition(作品,合成)

3.5 Adding new functions(新建函数)

function definition: A statement that creates a new function, specifying its name, parameters, and the statements it executes.

def(定义新的函数) is a keyword that indicates that this is a function definition.

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

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.")...

Defining a function creates a variable with the same name.The value of print_lyrics is a function object, which has type ‘function‘.
(用 print(函数名) ,输出函数类型和位置;用 type(函数名) ,输出函数类型)

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

3.6 Definitions and uses

3.7 Flow of execution

flow of execution(执行): The order in which statements are executed during a program run.

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.
(执行流程能让你更快看到执行代码,不用从上往下全部看一遍.)

3.8 Parameters and arguments(参数)

>>> def print_twice(bruce):    print(bruce)    print(bruce)>>> print_twice("hello world")hello worldhello world>>> print_twice(math.pi)3.1415926535897933.141592653589793

3.9 Variables and parameters are local

local variable: A variable defined inside a function. A local variable can only be used inside its function.

>>> def cat_twice(part1,part2):    cat=part1+part2    print_twice(cat)>>> cat_twice("hello","world")helloworldhelloworld

3.10 Stack diagrams

stack diagram: A graphical representation of a stack of functions, their variables, and the values they refer to.

3.11 Fruitful functions and void functions

fruitful function: A function that returns a value.(有返回值)

void function: A function that doesn’t return a value.(无返回值)

3.12 Why functions?

  • Creating a new function gives you an opportunity to name a group of statements,
    which makes your program easier to read 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.

3.13 Importing with from (用 from 调用函数和值等)

Python provides two ways to import modules:
Example:importing math.pi

The first way: When you import math, you get a module object named math.(第一种方法是直接调用函数所在的模块)

>>> import math>>> print(math)<module 'math' (built-in)>>>> print(math.pi)3.141592653589793

The second way:you can import an object from a module like this.(第二种方法是从某个模块中调用某一函数或者是值)

from math importt pi>>> from math import pi>>> print(pi)3.141592653589793

Or you can use the star operator to import everything from the module.(调用某个模块中所有函数或者值)

The advantage of importing everything from the math module is that your code can be more concise. The disadvantage is that there might be conflicts between names defined in different modules, or between a name from a module and one of your variables.

>>> from math import *>>> cos(pi)-1.0

3.14 Debugging

  • If you are using a text editor to write your scripts, to use spaces exclusively (no tabs). (在用文本编辑的时候,用空格键而不是tab键)
  • Tabs and spaces are usually invisible, which makes them hard to debug, so try to find an editor that manages indentation for you.
  • don’t forget to save your program before you run it.

3.16 Exercises

Exercise 3.3.

Python provides a built-in function called len that returns the length of a string, so
the value of len(’ allen’ ) is 5.
Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.

>>> def right_justify(s):    a=len(s) #将s的长度赋值到a    b=70-a #b是所要填补的空格的数量    print(b*' '+s) #输出b个空格加上s>>> right_justify('allen')                                                                 allen

Exercise 3.4.

A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:

>>> def do_twice(f):    f()    f()

Here’s an example that uses do_twice to call a function named print_spam twice.

>>> def do_twice(f):    f() #f是函数    f()>>> def print_spam(): #输出"spam",spam(翻译:垃圾邮件)    print('spam') >>> do_twice(print_spam)spamspam
  1. Type this example into a script and test it.
  2. Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
>>> def do_twice(f,s): #运行两次f()函数    f(s)    f(s)
  1. Write a more general version(版本) of print_spam , called print_twice, that takes a string as a parameter and prints it twice.
>>> def print_twice(s): #输出两次s    print(s)    print(s)
  1. Use the modified version of do_twice to call print_twice twice, passing ‘spam’ as an argument.
>>> do_twice(print_twice,"spam")spamspamspamspam
  1. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
>>> def do_four(f,s): #f为函数,s为值    do_twice(f,s)    do_twice(f,s)>>> do_four(print_twice,"spam") #do_four函数测试spamspamspamspamspamspamspamspam

Exercise 3.5.

This exercise can be done using only the statements and other features we have learned so far.
1. Write a function that draws a grid(格子) like the following:

Hint: to print more than one value on a line, you can print a comma(逗号) to separated sequence:(用逗号隔开多个变量)

    >>> print ('+','-')    + - #输出效果

【第二个功能在3.0版本不确定能否使用,反正我没用出来】
If the sequence ends with a comma , Python leaves the line unfinished, so the value printed next appears on the same line.
print ’ +’ ,
print ’ -’
The output of these statements is ’ + -’ .
A print statement all by itself ends the current line and goes to the next line.

def print_14141(a,b): #文本处理成14141类型的;    return (a+b*4)*2+a+'\n'def print_beam():    return print_14141('+','-')def print_line():    return print_14141('|',' ')def print_grid():    a=print_14141(print_beam(),print_line())    print(a);
>>> print_grid() #输出效果,完成+----+----+|    |    ||    |    ||    |    ||    |    |+----+----+|    |    ||    |    ||    |    ||    |    |+----+----+

补充:parameter和argument的区别

一直没搞太清 parameter和argument的区别

根据网上一些资料,对parameter和argument的区别,做如下的简单说明。
1. parameter是指函数定义中参数,而argument指的是函数调用时的实际参数。
2. 简略描述为:parameter=形参(formal parameter), argument=实参(actual parameter)。
3. 在不很严格的情况下,现在二者可以混用,一般用argument,而parameter则比较少用。

While defining method, variables passed in the method are called parameters.
当定义方法时,传递到方法中的变量称为参数.
While using those methods, values passed to those variables are called arguments.
当调用方法时,传给变量的值称为引数.(有时argument被翻译为“引数“)

0 0
原创粉丝点击