Read Think Python-ch3 Functions

Source: Internet
Author: User

Calling functions

In a program, a function is a named statement that carries out an operation. When you define a function, you need to indicate the name and the statement of the letter. The function can then be called through the function name. We've seen the function call :

>>> type (+)'int'>

The function name is type. An expression in parentheses is called a parameter to a function. The result of this function is the type of the return parameter.

In general, functions need to get parameters and return results. The result is called the return value .

Type conversion function

Python provides built-in functions to convert one type of value into another. The INT function converts any parameter value that can be converted to an integer, otherwise an error is indicated:

>>> int ('+ ') 32>>> int ('Hello' )   for int (): Hello

int can convert floating-point numbers to integers, but not rounding, but truncating fractional parts:

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

Float converts an integer or string into a floating-point number:

>>> Float (+)32.0>>> float ('3.14159') 3.14159

Finally, Str converts the arguments into a string:

>>> Str (+)' +'>>> str (3.14159)'  3.14159'

Mathematical functions

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

Before you can use it, you must first load it:

>>>Import Math

The above statement creates a module object called Math. If you print the module object, you can get some information about it:

Print Math ' Math ' (built-in) >

The module object contains the functions and variables defined therein. Using the functions in the module, you must write out the module name and function name, which are separated by dots. This format is called dot notation .

>>> ratio = signal_power/ noise_power>>> decibels = ten * math.log10 (ratio)>>& Gt radians = 0.7>>> height = math.sin (radians)

The first example uses LOG10 to calculate the Snr of the decibel (assuming Singal_power and noise_power have been defined). The Math module also provides log, which calculates the base e logarithm.

The second example is to calculate the cosine of a radian. Parameter variable name, which indicates that the parameters of sin or other trigonometric functions (Cos,tan, etc.) are radians. Divide by 360 times 2pi to convert the angle to radians:

 $ 360.0 2 * math.pi>>> math.sin (radians)0.707106781187

Structure

So far, the program elements we've touched--variables, expressions, and statements--are isolated, without saying how to put them together.

One of the important features of programming languages is to include small chunks of code and how to combine them. For example, a function's argument can be any expression that includes an arithmetic operator:

x = Math.sin (degrees/360.0 * 2 * Math.PI)

Even a function call:

x = Math.exp (Math.log (x+1))

Almost all places that require a value can be substituted with an expression, except for the left side of the assignment statement, which must be a variable name. Any expression on the left side will result in a syntax error (with exceptions, as described later).

#  Right # wrong! Syntaxerror:can't assign to operator

Custom functions

Currently, we only use Python's own functions, but we can also write a function ourselves. The function definition indicates the name of the function and the code that needs to be executed when the function is called.

As in the following 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 the keyword that defines a function. The name of the function is Print_lyrice. The rule of the function name is the same as the variable name rule: Letters, numbers, and some symbols are legal, but the first character cannot be a number. You can use the keyword as the function name, but you should avoid using the same name for variables and functions.

The parentheses after the function name are empty, indicating that the function has no arguments.

The first kind of function definition is called the head ; the rest is called the function body . The head ends with a colon, the function body must be indented, and the indentation is always 4 spaces; see Debugging section. The function body can protect any number of statements.

The string in the print statement is enclosed in double quotation marks. Single quotes and double quotes work the same way, in most cases using single quotes, unless, like above, the string contains single quotes (also called apostrophes).

If a function is defined in an interactive environment, the interpreter outputs an ellipsis (...). Hint, define whether to complete: //Try a bit Win7 2.7 and not ...

defprint"i ' m a lumberjack, and I ' m okay. "  print"I sleep all night and I work all day. " ...

At the end of the function, you must enter a blank line (in the script, you do not need to do so).

A function definition produces a variable with the same name.

Print print_lyrics<function print_lyrics at 0xb7e99e9c>>>> type (print_lyrics)' function '>

The value of Print_lyrice is a function object , and its type is ' function '.

The syntax for invoking a custom function is the same as the built-in function:

>>> print_lyrics () I'm A lumberjack, and I' and I Work all day.

After defining a function, you can use him in other functions, for example, repeating the above function two times, we can write a function called Repeat_lyrice:

def repeat_lyrics ():    print_lyrics ()    print_lyrics ( )

Then call Repeat_lyrice:

>>> repeat_lyrics () I'm A lumberjack, and I' and I Work all day. I'm A lumberjack, and I' and I work all day.

It's a pity the song doesn't sing that way.

Define and use

Putting the above pieces of code together will look 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 ()

This code consists of two function definitions: Print_lyrice and Repeat_lyrice. Defining a function again executes the same as other code, just creating a function object. The statement inside the function does not execute until it is called, and the general function definition has no output.

As you would expect, you must create it before the function executes. In other words, the statement of the function definition must be executed before the first function call.

Exercise 3-1

Move the last line of the above program to the first line so that the function call appears before the definition. Run the program and see what the error message is.

Nameerror:name ' repeat_lyrics ' is not defined

Exercise 3-2

Put the function call statement to the end, put the print_lyrice definition behind the Repeat_lyrice, and run what happens.

Success

Run the process

To ensure that the function is defined before the first call, you must understand the order in which the code is run, called, and run the process .

The program always executes from the first line of code. Statements are executed sequentially from top to bottom.

The function definition does not alter the order of code execution, but remember that the code in the function definition does not execute, knowing that it is called.

A function call would like to run the process around the bend. Instead of executing the next line of code, jump to the body of the function, execute all the code of the function body, and then go back to where you were just now.

This sounds simple, but one function calls the other one is not easy. In the middle of the function body, the program may execute code in another program. However, during the execution of this function, the code of another function may be executed.

Fortunately, Python can remember very well which line to run, each time the function is called, the program goes back to the function that was just not completed and called. Finish running all the code.

What does it mean? When you read a program, you don't have to go from the first line to the last line every time. Sometimes it's easier to understand how to read in a running process.

Formal parameters and arguments

We see that some of the built-in functions require arguments. For example, call Math.sin must pass a numeric value as an argument. Some functions have more than one argument, for example Math.pow has two, cardinality, and exponent.

Inside the function, the argument is copied to the parameter variable. Here's an example where a user-defined function has a parameter:

def Print_twice (Bruce):     Print Bruce     Print Bruce

This function passes the arguments to the shape parametric Bruce. When the function is called, print the parameter two times.

Any value that can be printed, the function can be run.

>>> print_twice ('Spam') spamspam>>> Print_twice (  )1717>>> print_twice (math.pi)3.141592653593.14159265359

The same rules as structs can be applied to built-in functions and custom functions, so I can use any expression as an print_twice argument.

>>> print_twice ('*4) Spam Spam Spam spamspam Spam Spam Spam> >> Print_twice (Math.Cos (Math.PI))-1.0-1.0

Parameters are evaluated before the function call, so in the example above, ' Span ' and Math.Cos (Math.PI) are calculated only once.

You can also use a variable as an argument to a function:

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

Slightly

Variables and formal parameters are local

Define a variable inside the function, which is local , that is, it is only valid inside the function, for example:

def Cat_twice (part1, part2):     = Part1 + part2    print_twice (cat)

This function has two parameters, connects them, and prints two times, here is a running example:

"'tiddle bang.  '>>> cat_twice (line1, line2) Bing tiddle Tiddle Bang. Bing tiddle Tiddle Bang.

When the Cat_twice run is finished, the variable cat is recycled. If we try to print it, we get an error:

Print'cat' is not defined

Formal parameters are also local variables. For example, the function print_twice outside and there is no Bruce variable.

Stack diagram

To understand where each variable is available, it is sometimes useful to draw a stack diagram . Just like the program flowchart, the stack diagram indicates the value of each variable, and also indicates which function the variable belongs to.

Each function is represented by a frame. The frame is a box next to the function name, which is the function's parameter and variable name. The above example of the stack figure 3-1.

The framework is allocated in stack memory to indicate which function calls which, and so on. In this example, Print_twice is called by Cat_twice, Cat_twice is called by __main__, and __main__ is the special name of the top-level frame. If you create a variable that is outside any function, it belongs to __main__.

Each parameter points to the same value as the parameter. Therefore, the value of Part1 is the same as line1, and the value of Part2 is the same as line2, and Bruce has the same value as cat.

If an error occurs during a function call, the Python prints the function name and the name of the function that called it, and the name of the function that called the function, so go down to __main__.

For example, if you try to use Cat in Print_twice, a variable name error will be generated:

Traceback (innermost last): File"test.py", Line 13,inch __main__Cat_twice (line1, line2) File"test.py", Line 5,inchCat_twice Print_twice (cat) File"test.py", Line 9,inchPrint_twicePrintCatnameerror:name'Cat'  is  notDefined

This string of functions is called backtracking . It tells you which program file is on which line, and what function is executed with an error. Shows which line of code the error occurred.

The sort of backtracking function is the same as the sort of frame in the stack diagram. When an error occurs, the function that is running is listed at the bottom.

Functions with return values and no return values

Some functions we use to produce results, such as mathematical functions, because there is no better name, we call it a function with a return value . Other functions, such as Print_twice, operate, but do not return a value. They are called functions that have no return value .

When you call a function that has a return value, you mostly want to use the function result; For example, copy it to a variable or use it as part of an expression:

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

If a function is called in an interactive environment, Python will show the result of the function:

>>> math.sqrt (5)2.2360679774997898

However, in a script, if you just call a function that has a return value, the return value is discarded!

MATH.SQRT (5)

This script calculates the square root of 5, but does not save or show the result, so it is not used.

A letter with no return value may be output on the screen, or have some other effect, but no return value. If you try to copy the result to a variable, you get a special value called None.

>>> result = Print_twice ('Bing') bingbingprint  resultnone 

The none value differs from the string ' None '. It is a special value that has its own type:

Print type (None) ' Nonetype '>

All of the functions we write now have no parameters. In later chapters, you will start writing functions with parameters.

Why use a function?

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

    • Creating a function can name a piece of code, which is good for the program to read and Debug.
    • Make the program look more concise because it removes duplicate code. Also, if you need to change it, just change it once.
    • Dividing a long program into functions allows you to debug only a piece of code, debug it, and then put it together to run.
    • Well-designed functions can be applied to multiple programs. Write well and debug a function that can be used multiple times.

Using the From Import

Python provides two ways to import modules; we've seen one of them:

Import Math Print Math ' Math ' (built-inprint  math.pi3.14159265359

If you import math, you get a module object called Math. Module objects contain constants, such as Pi, and functions, such as SIN and exp.

But if you want to use PI directly, you get an error.

Print"<stdin>" in <module> '  Pi' is not defined

Another way, you can import objects from a module, for example:

 from Import Pi

Now you can use PI directly, and you don't need a dot tag.

Print Pi3.14159265359

Alternatively, you can use the asterisk (*) to export all the contents of the module:

 from import *>>> cos (PI)-1.0

The benefit of importing all the contents of the math module is that the code becomes more concise. The downside is that the naming of different modules can conflict, or the module conflicts with the variable names defined in the work environment.

Debugging

If you use a text editor to write scripts, you may run with errors due to the use of spaces and tabs. The best way to avoid this is to use only spaces (without tabs). Many text editors know Python, which is done by default, but some do not.

Tabs and spaces are invisible, so it's hard to debug, so find yourself an editor that's easy to indent.

Don't forget to save the program before you run it. Some development environments will be saved automatically, but some will not. This way, it is possible that the program you are looking at in the editor is not the same as the actual operation.

Debugging may take a long time if you have been running this same, incorrect program.

Make sure that the code you see is running. If you are unsure, enter some code similar to print ' Hello ' in front of the program and run again. If you do not see Hello, the code is not running correctly.

Vocabulary List

Function:

A named statement that is used to perform an operation. The function may have parameters and no parameters, there may be return values, and no return values.

function definition:

Create a statement of a new function that indicates the name of the function, the parameters, and the code to execute.

Function object:

A value created by the function definition. A function name is a variable that points to a functional object.

(function) Header:

The first line of the function definition

(function) Body:

A section of a statement in a function definition.

Formal parameters:

A variable name used in the function that points to the value passed by the argument.

Function call:

The code that executes the function. Consists of the function name and the list of arguments followed.

Actual parameters:

A value that is passed to a function when it executes. This value is passed to the corresponding parameter when the function is defined.

Local variables:

Variables defined inside the function. Local variables can only be used inside a function.

return value:

The result of the function. If the function is called as an expression, the return value is also the value of the expression.

Functions with return values:

A function that has a return value.

function with no return value:

Functions that do not return any values.

Module:

A file that contains the relevant functions and some other definitions.

Import statement:

A statement that can read module files and create module objects.

Module object:

The import statement creates a value that allows access to the values defined in the module.

Dot notation:

A syntax for invoking a function in a module, writing out the name of a module, followed by a dot (a solid period), and then the name of the function.

Composition:

Use an expression as part of another larger expression, or a statement as part of another larger statement.

Run the process:

The order in which the statements run during the program run.

Stack diagram:

The stack of functions is represented by graphs, including variables, and values that the variables point to.

Framework:

A box used in a stack diagram to represent a function call. Includes parameters for local variables and functions.

Backtracking:

Runs a list of functions that are output when an error occurs.

Read Think Python-ch3 Functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.