Python function learning Notes

Source: Internet
Author: User
Tags call back cos error code function definition natural logarithm sin sleep square root


1. Function call

In programming, a function is a name combination of a series of statements used for a certain calculation. When defining a function, you must specify the function name and write a series of program statements. Then, you can use the name to "call" the function. We have seen examples of function calls before:

>>> Type (32)
<Type 'int'>
The name of this function is type, and the expressions in parentheses are called function parameters. The result of this function call is of the parameter type.

We usually say that the function "receives" parameters and "returns" results. This result is called return value ).

2 Type conversion functions
Python provides some built-in functions that can convert a value from one type to another. The int function can convert any value that can be converted to an integer. If the conversion fails, an error is returned:

>>> Int ('32 ')
32
>>> Int ('Hello ')
ValueError: invalid literal for int (): Hello
Int can be used to convert a floating point number to an integer without rounding it. Instead, it directly discards the fractional part.

>>> Int (3.99999)
3
>>> Int (-2.3)
-2
The float function converts integers and strings to floating-point numbers:

>>> Float (32)
32.0
>>> Float ('3. 14159 ')
3.14159
Finally, the str function converts parameters to strings:

>>> Str (32)
'32'
>>> Str (3.14159)
'3. 100'
3 Mathematical functions
Python has a mathematical computing module that provides most common mathematical functions. A module is a file that contains a set of related functions.

To use a module, you must first import it into the (import) runtime environment:

>>> Import math
This statement creates a module object named math ). If you print this object, you can see some information about it:

>>> Print math
<Module 'math' (built-in)>
The module object contains the functions and variables defined in this module. To access a function, you must specify both the module name and function name and separate them with 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)
In the first example above, log10 is used to calculate the signal/noise ratio in decibels (assuming that both signal_power and noise_power have been defined in advance ). The math module also provides log functions to calculate the natural logarithm of the base e.

The second example calculates the sine of radians. This variable name implies that the parameters accepted by sin, cos, tan, and other trigonometric functions are radians. To convert degrees to radians, divide them by and multiply them by 2 & pi ;:

>>> Degrees = 45
>>> Radians = degrees/360.0*2 * math. pi
>>> Math. sin (radians)
0.707106781187
The expression math. pi obtains the variable pi from the math module. The value of this variable is an approximate value of & pi;, which is approximately 15 digits.

If you know the trigonometric function, you can compare the above result with half of the square root of 2:

>>> Math. sqrt (2)/2.0
0.707106781187
4 combination
So far, we have learned about the basic elements of the program, including variables, expressions, and statements, but have not yet come into contact with how to organically combine them.

One of the most useful features of a programming language is the ability to combine various small building blocks. For example, a function parameter can be an expression of any type, including an arithmetic symbol:

X = math. sin (degrees/360.0*2 * math. pi)
It even includes function calls:

X = math. exp (math. log (x + 1 ))
Basically, any expression can be used in any place where values can be used. There is only one exception: the variable name must be on the left of the value assignment expression, placing any other expressions on the left is a syntax error (we will see exceptions for this rule later ).

>>> Minutes = hours * 60 # Correct
>>> Hours * 60 = minutes # Error!
SyntaxError: can't assign to operator
5. Add a new function.
At this point, we are only using functions provided by Python. In fact, we can also add new functions by ourselves. Function definition specifies the name of the new function and provides a series of program statements. When a function is called, these statements are executed sequentially.

The following 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, indicating a function definition. The name of this function is print_lyrics. Function names are written in the same way as variable names: letters, numbers, and some punctuation marks are valid, but the first character cannot be a number. The keyword cannot be used as the function name, and we should try to avoid the same name between the function and the variable.

The empty parentheses after the function name indicate that it does not receive any parameters.

The first line of the function definition is called the function header, and the rest is called the function body ). The function header should end with a colon, and the function body is indented first. By convention, indentation always uses four spaces. See section 3.14. The number of code statements in the function body is unlimited.

In this example, the strings in the print statement are enclosed in double quotation marks. Single quotes and double quotes have the same effect. In most cases, single quotation marks are used. Double quotation marks are used only in special cases like this. In this example, the string itself contains single quotation marks (single quotation marks are also used as omitted symbols, such as I'm ).

If you enter a function definition in interactive mode, the interpreter will output a ellipsis (...) prompting you that your current definition is not over yet:

>>> 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 definition of this function, enter a blank line (this is not required in the script file ).

After a function is defined, a variable with the same name is created.

>>> Print print_lyrics
<Function print_lyrics at 0xb7e99e9c>
>>> Type (print_lyrics)
<Type 'function'>
The value of the variable print_lyrics is a function object and its type is 'function '.

You can call a newly created function in the same way as calling a built-in function:

>>> Print_lyrics ()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
After defining a function, you can call it in other functions. For example, if you want to repeat the above lyrics, you can write a repeat_lyrics function:

Def repeat_lyrics ():
Print_lyrics ()
Print_lyrics ()
Then you can 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.
Of course, this song is not actually so sung.

6. Define and use
Integrate the scattered code in the previous section. The whole program looks like the following:

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 program contains two function definitions: print_lyrics and repeat_lyrics. (When the interpreter executes the program code) the execution method of the function definition is the same as that of other statements. The difference is that the function object will be created after execution. The statements in the function body are not executed immediately, but are executed only when the function is called. Function definition does not produce any output.

As you may have guessed, you must first create a function to execute it. In other words, the function definition must be executed before the first call of the function.

Exercise 1
Move the last line of the program to the first line, so the function call is executed before the function definition. Run the program and view the error information.

Exercise 2
Put the row of the function call back to the end, and put the definition of the function print_lyrics after the definition of the function repeat_lyrics. What will happen when running the program?

7. Execution process
To ensure that the definition of a function is executed before its first call, you need to know the statement execution sequence in the program, that is, the execution process.

Execution always starts from the first line of the program. From top to bottom, one statement is executed each time in order.

The function definition does not change the execution process of the program. However, you should note that the statements in the function body are not executed immediately, but are executed when the function is called.

Function calling can be seen as a roundabout path in the program execution process. When a function is called, it does not directly execute the next statement. Instead, it jumps to the first line of the function body, continues to execute all the statements of the function body, and then jumps back to the original place.

This seems simple, but you will soon find that other functions can be called in the function body. When a program flow runs into a function, you may need to execute statements in other functions. However, when executing the statement in that function, you may need to call the statement to execute another function!

Fortunately, Python has a good record of where it runs, so after each function is executed, the program can jump back to where it leaves. The program will not end until it is executed to the end of the entire program.

What is the meaning of the previous boring description? When you read the code, you should not always read a line in the writing order. Sometimes it may be better to read the code according to the execution process.

8 parameters and real parameters ①
As we can see, some built-in functions need to input parameters. For example, when you call math. sin, you need to input a number as the real parameter. Some functions require multiple arguments: math. pow requires two arguments: base and exponent ).

Inside the function, the real parameter is assigned to the form parameter. The following example shows a user-defined function that receives a real parameter:

Def print_twice (bruce ):
Print bruce
Print bruce
When calling this function, the value of the real parameter is assigned to the parameter bruce and printed twice.

This function is available for any printable value.

>>> Print_twice ('SPAM ')
Spam
Spam
>>> Print_twice (17)
17
17
>>> Print_twice (math. pi)
3.14159265359
3.14159265359
The combination rules of built-in functions are also available in user-defined functions, so we can use any expression for print_twice as the real parameter:

>>> Print_twice ('spam' * 4)
Spam
Spam
>>> Print_twice (math. cos (math. pi ))
-1.0
-1.0
The expression used as a real parameter is executed before the function is called. In this example, the expressions 'spam' * 4 and math. cos (math. pi) are executed only once.

You can also use variables as real parameters:

>>> Michael = 'Eric, the half a bee .'
>>> Print_twice (michael)
Eric, the half a bee.
Eric, the half a bee.
The name (michael) of the variable passed into the function as the real parameter does not matter with the name (bruce) of the form parameter in the function definition. The function only cares about the value of the parameter, rather than the name before it is called. In the print_twice function, everyone is called bruce.

9. The variables and parameters are local.
When you create a variable in a function, it is local, that is, it only exists in this function. For example:

Def cat_twice (part1, part2 ):
Cat = part1 + part2
Print_twice (cat)
This function receives two real parameters, concatenates them, and prints the results twice. The following is an example of using this function:

>>> Line1 = 'Bing tiddle'
>>> Line2 = 'tiddle bang .'
>>> Cat_twice (line1, line2)
Bing tiddle bang.
Bing tiddle bang.
When cat_twice ends, the variable cat will be destroyed. If you try to print it again, an exception will be returned:

>>> Print cat
NameError: name 'cat' is not defined
The parameter is also local. For example, in the variables print_twicebruce.

10 Stack Diagram
It is easy to draw a stack diagram to track where variables are used. Like a status chart, a stack chart shows the values of each variable. The difference is that it displays the function to which each variable belongs.

Each function uses a frame to contain. In the stack diagram, a frame is a box with a function name, which contains function parameters and variables. The Stack Diagram of the previous function example is shown in Figure 1.

 

Figure 1 Stack Diagram

In the figure, each frame is arranged as a stack from top to bottom to show which function is called. In this example, printtwice is called by cattwice, while cattwice is called by main. _ Main is the special name used to represent the entire stack graph. When you create a variable outside of all functions, it belongs to _ main.

Each form parameter points to the same value as its corresponding real parameter. Therefore, the values of part1 and line1 are the same, the values of part2 and line2 are the same, and the values of bruce and cat are the same.

If an error occurs during the function call process, Python prints the function name, the name of the function that calls the function, and the name of the function that calls the caller.

For example, if you access the cat variable in print_twice, you will get a NameError:

Traceback (innermost last ):
File "test. py", line 13, in _ main __
Cat_twice (line1, line2)
File "test. py", line 5, in cat_twice
Print_twice (cat)
File "test. py", line 9, in print_twice
Print cat
NameError: name 'cat' is not defined
The above function list is called traceback ). It tells you which program file, which line the error occurs, and which functions are running. It also displays the line of code that causes the error.

The order of functions in backtracking is the same as that in the graph. The currently executed function is listed at the bottom.

11 There are return and no return functions
Some of the functions we have used, such as mathematical functions, will produce results. Because I didn't think of a better name, I call this type of function as a function with a returned value (fruitful function ). Some other functions, such as print_twice, execute an action without returning any value. This type of function is called void function ).

When you call a function with a returned value, you usually want to perform some operations on the result. For example, you may want to assign a value to a variable or use it in an expression:

X = math. cos (radians)
Golden = (math. sqrt (5) + 1)/2
When calling a function in interactive mode, Python directly displays the result:

>>> Math. sqrt (5)
2.2360679774997898
However, in a script, if you just call this type of function, its return value will be lost forever!

Math. sqrt (5)
This script calculates the square root of 5, but it does not actually work because it does not store or display the calculation results in a variable.

A function without return values may display something on the screen or have other effects, but they do not return values. If you try to assign their results to a variable, you will get a special value of None.

>>> Result = print_twice ('Bing ')
Bing
Bing
>>> Print result
None
The value None is different from the string 'none. It is a special value and has its own unique type:

>>> Print type (None)
<Type 'nonetype '>
So far, all our custom functions have no return value functions.

12. Why are functions required?
Why does it take time to split a program into functions? The reasons may not be clear at the beginning of programming. The following explanations can be used as a reference.

Creating a new function gives you the opportunity to name a group of statements, making the code easier to read and debug.
The function can shorten the program by reducing repeated code. If you need to modify the code later, you only need to modify it in one place.
After splitting a long program into several functions, you can debug each function separately and assemble it into a complete product.
A well-designed function can be used in many programs. Write once, debug once, reuse infinite.
13 use the from import Module
Python provides two import modules. We have seen one of them:

>>> Import math
>>> Print math
<Module 'math' (built-in)>
>>> Print math. pi
3.14159265359
If you import math, you will get the module object named math. The module object contains constants such as pi and functions such as sin and exp.

However, if you directly access pi, an error occurs.

>>> Print pi
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
NameError: name 'pi 'is not defined
At this time, you can import an object in the module as follows:

>>> From math import pi
Now you can directly access pi without using the period representation math. pi.

>>> Print pi
3.14159265359
Alternatively, you can use an asterisk to import all the members of a module:

>>> From math import *
>>> Cos (pi)
-1.0
The advantage of using this method to import all the members in the module is that you can make your code more concise, but the disadvantage is that the members of different modules with the same name or between them and custom variables, a name conflict may occur.

14 debugging
If you use a text editor to write scripts, you may encounter indentation and tab confusion issues. The best way to avoid this problem is to use only spaces (without tabs ). Most text editors that recognize Python do this by default, but some do not.

Tabs and spaces are invisible, making debugging difficult. Therefore, you should try to find an editor that can help you deal with indentation.

In addition, do not forget to save it before running the program. Some development environments are automatically saved, but some are not automatically saved. If you do not save the code, the code you write is not the same as the code you run.

If the error code you run is different from the code you write, debugging will waste a lot of time!

Make sure that the code you see is consistent with the code you run. If you are not sure, you can write a print 'hello' at the beginning of the program and run it again. If no hello output is displayed, you are not running the correct program!

15 Glossary
Function: a sequence of named statements that can be used for some useful operations. The function can receive or not receive parameters. It can return or not return results.

Function definition: a statement used to create a new function, specifying the function name, parameters, and the sequence of statements it executes.

Function object: defines the value created by the function. The function name can be used as a variable to reference a function object.

Function header: the first line of function definition.

Body: The sequence of statements in the function definition.

Parameter: the name used in the function to reference the value passed in as a real parameter.

Function call: executes a function statement. It consists of the function name and parameter list.

Real parameter (argument): the value provided to the function when it is called. This value is assigned to the corresponding parameter.

Local variable: the variable defined in the function. Local variables can only be used in functions.

Return value: the result of the function. If a function is called as an expression, the return value is the value of the expression.

Fruitful function: a function that returns a value.

Void function: a function without a return value.

Module: A file that contains related functions and other defined sets.

Import statement: a statement that reads a module file and creates a module object.

Module object: the object created when the import statement is used to access the value defined in the module.

Dot notation: Call the syntax of a function in another module. Add the previous period to the module name, and then add the function name.

Composition: use an expression as part of a larger expression, or use a statement as part of a larger statement.

Execution flow (flow of execution): the sequence in which statements are executed while the program is running.

Stack digraphs: graphical representations of function stacks, their variables, and the values referenced by these variables.

Frame: a frame in a stack diagram that represents a function call. It contains local variables and function parameters.

Traceback: prints the function stack being executed when an exception occurs.

16 exercises
Exercise 3 Python provides a built-in function len that returns the length of a string. So the len ('Allen ') value is 5.

Write a function right_justify, receive a string parameter s, and print enough leading spaces to display the last character in column 70th.

>>> Right_justify ('Allen ')
Allen
Exercise 4: a function object is a value. You can assign it to a variable or pass it as a real parameter. For example, do_twice is a function that receives a function object as a real parameter and calls it twice:

Def do_twice (f ):
F ()
F ()
The following is an example of using do_twice to call a print_spam function twice:

Def print_spam ():
Print 'spam'

Do_twice (print_spam)
1. Save this example to the script and test it.

2. Modify do_twice to receive two real parameters. One is a function object and the other is a value. It calls the function object twice and passes in the value as the real parameter.

3. Write a more general print_spam called print_twice, receive a string parameter, and print it twice.

4. Use the modified do_twice to call print_twice twice and pass in the real parameter 'spam '.

5. Define a new function do_four, receive a function object and a value, and use this value as the real parameter to call the function four times. The function body of this function should have only two statements, not four.

Exercise 5: This exercise can be implemented with only the statements and other language features we have learned.

1. Compile a function and draw the following table:

 

Prompt
:

To print multiple values in the same line, you can use commas to separate different values:

Print '+ ','-'
If there is a comma at the end of the value sequence, Python will not wrap the line, so the following print statement will appear in the same line.

Print '+ ',
Print '-'
The output of these two statements is '+ -'. 2. Write a function to draw a similar table, but there are four rows and four columns.

Related Article

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.