Describes how to use python parameters and scopes.

Source: Internet
Author: User

This article describes how to organize a statement into a function. It also describes the concepts of parameters and scopes, as well as the concept of recursion and its usage in the program.
1. Create a function
A function can be called. It executes an action and returns a value. Use the def statement to define a function: (not all functions return something)
Copy codeThe Code is as follows:
Def fibs (num ):
Result = [0, 1]
For I in range (num-2 ):
Result. append (result [-2] + result [-1])
Return result

Record Function
If you want to write a document to the function for understanding, you can add a comment (starting ). Another way is to write the string directly, which will be stored as part of the function, which becomes the document string.
Copy codeThe Code is as follows:
Def square (x ):
'Calculate the square of x'
Return x * x

# The document string can be accessed as follows:
>>> Square. _ doc _
'Calculate the square of x'

2. Parameter magic
Functions are easy to use and are not complex to create. However, the usage of function parameters is sometimes incredible.
2.1 can I change the parameters?
Assign a new value to the parameter in the function, without changing the value of any external variable:
Copy codeThe Code is as follows:
>>> Def to_change (n ):
N ='s'
>>> Name = 'B'
>>> To_change (name)
>>> Name
'B'

Strings (numbers and metadata) cannot be modified. However, if you use a variable data structure such as a list as a parameter, the parameter will be changed.
Copy codeThe Code is as follows:
>>> Def change (n ):
N [0] = 'ss'
>>> Names = ['A', 'zs']
>>> Change (names)
>>> Names
['Ss', 'zz ']


2.2 keyword parameters and default values
So far, all the parameters we use are called location parameters. Sometimes the order of parameters is hard to remember. To make things easier, you can provide the parameter name:
Copy codeThe Code is as follows:
>>> Def hello (greeting, name ):
Print '% s, % name! '
>>> Hello (greeting = 'hello', name = 'World ')
Hello, world!

In this way, the parameter order is completely unaffected, but the parameter names and values must correspond.
In this way, the parameter provided by the parameter name is called a keyword parameter. The main function is to clarify the role of each parameter.
The most powerful keyword parameter is that the default value can be provided to the parameter in the function:
>>> Def hello (greeting = 'hello', name = 'World '):
Print '% s, % name! '
When a parameter has a default value, you do not need to provide IT when calling it. You can provide some or all parameters.
Copy codeThe Code is as follows:
>>> Hello ()
'Hello, world! '
>>> Hello ('greeting ')
'Greeting, world! '
>>> Hello (name = 'Universe ')
'Hello, universe! '
 
2.3 collect Parameters
If the function can store multiple names, you can provide the function with any number of parameters. We need to do this: provide a parameter when defining the function and add an asterisk before it.
Copy codeThe Code is as follows:
>>> Def print_para (* paras ):
Print paras
>>> Print_para ('ss ')
('Ss ',)
>>> Print_para (1, 2, 3)
(1, 2, 3)

The asterisks before the parameter place all values in the same tuples. It can be said that these "parameters in other locations" are collected before use. If no collection element is provided, the parameter returns an empty tuples ().
However, to process the "Collection" Operation of keyword parameters, we need two asterisks "**":
Copy codeThe Code is as follows:
>>> Def print_params (x, y, z = 3, * pospar, ** keypar ):
Print x, y, z
Print pospar
Print keypar

>>> Print_params (1, 2, 3, 5, 6, 7, foo = 1, bar = 2)
1 2 3
(5, 6, 7)
{'Foo': 1, 'bar': 2}
>>> Print_params (1, 2)
1 2 3
()
{}

In the preceding example, the first three parameters are fixed, and the fourth parameter pospar is a location parameter. Multiple parameters can be collected, and the fifth parameter is a keyword parameter, multiple keyword parameters can be collected. When no input is made, empty tuples or dictionaries are used by default.

2.4 reversal process
I have just discussed how to collect parameters as tuples and dictionaries. If you use * and *, you can perform the opposite operation. (1) Use
Copy codeThe Code is as follows:
>>> Def add (x, y ):
Return x + y
>>> Params = (1, 2)
>>> Add (* params)
3

(2) used in Definition
Copy codeThe Code is as follows:
>>> Def with_stars (** kds ):
Print kds ['name'], 'is, kds ['age'], 'ears old'
>>> Args = {'name': 'Mr. gumby', 'age': 42}
>>> With_stars (** args)
Mr. Gumby is 42 years old
 
Iii. Scope
After the value assignment statement x = 1 is executed, the name x is referenced to the value 1. Just like using a dictionary, the key references the value. Of course, the variable and the corresponding value use an invisible dictionary. The built-in vars function returns this dictionary:
Copy codeThe Code is as follows:
>>> X = 1
>>> Scope = vars ()
>>> Scope ['X']
1
>>> Scope ['X'] + = 1
>>> X
2

This invisible dictionary is called a namespace or scope. In addition to the global scope, each function call creates a new scope.
I generally know what scope is when I have learned programming. I will not go into detail here.

Iv. Recursion
Recursive definitions include references to their own definition content.
A useful recursive function contains the following parts:
(1) There are basic instances when the function directly returns values (minimum possibility problem)
(2) recursive instances, including recursive calls of the smallest part of one or more problems.
The key here is to break down the problem into a small part. recursion cannot continue forever, because it always ends with the least possibility problem, and these problems are stored in the basic instance.
Here are three typical recursive examples:
A. factorial
>>> Def factorial (n ):
If n = 1:
Return 1
Else:
Return n * factorial (n-1)
[/Code]
B. Power
Copy codeThe Code is as follows:
>>> Def power (x, n ):
If n = 0:
Return 1
Else:
Return x * power (x, n-1)

C. Binary Search (assuming that number must be in sequence)
Copy codeThe Code is as follows:
>>> Def search (sequence, number, lower, upper ):
If lower = upper:
Assert num = sequence [upper]
Return upper
Else:
Middle = (lower + upper) // 2
If number> sequence [middle]:
Return search (sequence, number, middle + 1, upper)
Else:
Return search (sequence, number, lower, middle)

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.