Explain the use of Python parameters and scopes _python

Source: Internet
Author: User
Tags vars
This article describes how to organize statements into functions, and describes the concepts of parameters and scopes, as well as the concept of recursion and its use in programs.
I. Creating a function
A function can be invoked, it performs some behavior, and returns a value. You can define a function with a DEF statement: (Not all functions will return something)
Copy Code code as follows:

def fibs (num):
result = [0,1]
For I in Range (num-2):
Result.append (Result[-2]+result[-1])
return result

Logging functions
If you want to write a document for the function to be understood, you can add a comment (beginning with #). Another way is to write the string directly, which is stored as part of the function, which becomes the document string.
Copy Code code as follows:

def Square (x):
' Calculate the square of X '
Return x*x

#文档字符串可以按如下方式访问:
>>> SQUARE._DOC_
' Calculate the square of X '

two. Parameter Magic
Functions are simple to use and are not complex to create, but the use of function parameters is sometimes inconceivable.
2.1 Can I change the parameters?
Assigning a new value to a parameter within a function does not change the value of any external variable:
Copy Code code as follows:

>>> def to_change (n):
n = ' s '
>>> name = ' B '
>>> To_change (name)
>>> Name
' B '

strings (and numbers and tuples) are immutable and cannot be modified. However, when you use a variable data structure such as a list as a parameter, the parameters are changed.
Copy Code code as follows:

>>> def Change (n):
N[0] = ' ss '
>>> names = [' AA ', ' ZZ ']
>>> Change (names)
>>> names
[' SS ', ' ZZ ']


2.2 keyword parameters and default values
So far, the parameters we use are called positional parameters. Sometimes the order of parameters is difficult to remember, in order to make things simpler, you can provide the name of the parameter:
Copy Code code as follows:

>>> def hello (greeting,name):
print '%s,%name! '
>>> Hello (greeting = ' Hello ', name = ' World ')
hello,world!

As a result, the parameter order is completely unaffected, but parameter names and values must correspond.
The parameters provided by using the parameter name are called keyword parameters, and the main function is to clarify the function of each parameter.
The most powerful thing about keyword parameters is that you can provide a default value to a parameter in a function:
>>> def hello (greeting = ' Hello ', name = ' World '):
print '%s,%name! '
When a parameter has a default value, the call does not provide arguments, can not provide, provide some or provide all the parameters.
Copy Code code as follows:

>>> Hello ()
' hello,world! '
>>> hello (' greeting ')
' greeting,world! '
>>> Hello (name = ' Universe ')
' hello,universe! '

2.3 Collecting parameters
If you can store more than one name in a function, the user can give the function any number of parameters, we need to do this: the function is defined by providing a parameter, preceded by an asterisk.
Copy Code code as follows:

>>> def Print_para (*paras):
Print Paras
>>> Print_para (' SS ')
(' SS ',)
>>> Print_para (1,2,3)
(1, 2, 3)

The asterisk in front of the parameter places all values in the same tuple, so you can say that these "parameters for the rest of the positions" are collected and reused. If no collection element is provided, the parameter gets a null tuple ().
But if you need to handle the "collect" operation of the keyword parameters, we need 2 asterisks "* *":
Copy Code code 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
()
{}

Please savor the above example, the first three parameters are fixed, the fourth parameter pospar is the position parameter, you can collect multiple parameters, the fifth parameter is a keyword parameter, you can collect multiple keyword parameters. When there is no input, the default is an empty tuple or an empty dictionary.

2.4 Reversal Process
You've just discussed how to collect parameters as tuples and dictionaries, and you can do the opposite if you use * and * *. (1) Use when calling
Copy Code code as follows:

>>> def Add (x,y):
Return X+y
>>> params = (1,2)
>>> Add (*params)
3

(2) to use when defining
Copy Code code as follows:

>>> def with_stars (**KDS):
Print kds[' name ', ' is ', kds[' age ', ' years '
>>> args = {' name ': ' Mr.gumby ', ' Age ': 42}
>>> With_stars (**args)
Mr.gumby is years old

three. Scope
After the X=1 assignment statement is executed, name x refers to the value 1. This is like using a dictionary, the key refers to the value, of course, the variable and the corresponding value is a ' invisible ' dictionary. The built-in VARs function can return this dictionary:
Copy Code code 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.
Generally learned to program the basic know what is the scope, here is not detailed.

Four. Recursion
The definition of recursion includes references to content that they define themselves.
A useful recursive function contains the following sections:
(1) There is a basic instance when the function returns the value directly (the least possible problem)
(2) Recursive instances, including a recursive invocation of one or more of the few problems.
The key here is to break the problem down into small pieces, and recursion cannot go on forever because it always ends up with the smallest possible problem that is stored in a basic instance.
Here's a look at 3 classic recursive examples:
A. Factorial
>>> def factorial (n):
if n = 1:
Return 1
Else
return n * Factorial (n-1)
[/code]
B. Power
Copy Code code as follows:

>>> def Power (x,n):
If n = 0:
Return 1
Else
return x * Power (X,N-1)

C. Two-dollar lookup (assuming number must be in sequence sequence)
Copy Code code 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)

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.