Explaining the use of Python parameters and scopes

Source: Internet
Author: User
Tags vars
This article describes how to organize statements into functions, and also details the concepts of parameters and scopes, as well as the concept of recursion and its purpose in the program.
I. Creating a function
A function can be called, which performs some behavior and returns a value. A function can be defined with a DEF statement: (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


Logging functions
If you want to write a document to the function to make it understandable, 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 CodeThe code is as follows:


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


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

two. Parametric magic
Functions are simple to use and are not complex to create, but the usage 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 CodeThe code is 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, if a mutable data structure such as a list is used as a parameter, the parameters are changed.
Copy CodeThe code is 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 have used are called positional parameters. Sometimes the order of parameters is difficult to remember, in order to make things easier, you can provide the name of the parameter:
Copy CodeThe code is as follows:


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


In this way, the order of the parameters is completely unaffected, but the parameter names and values must correspond.
This parameter, which is provided with parameter names, is called a keyword parameter, and the main function is to clarify the role of each parameter.
The most powerful thing about keyword parameters is that you can give 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, it is called without supplying arguments, and can be supplied with or provided with all parameters.
Copy CodeThe code is 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, you can give the function an arbitrary number of arguments, and we need to do this: provide a parameter when defining the function, and precede with an asterisk.
Copy CodeThe code is as follows:


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


The asterisk before the parameter places all values in the same tuple, which can be said to be used to collect these "parameters from the rest of the position". If no collection element is provided, the parameter is given an empty tuple ().
However, if you need to handle the "collect" operation of the keyword parameter, we need 2 asterisks "* *":
Copy CodeThe code is as follows:


>>> def print_params (x,y,z=3,*pospar,**keypar):
Print x, y
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 3
()
{}


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

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


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


(2) Use at the time of definition
Copy CodeThe code is 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, the name X is referenced 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 CodeThe code is as follows:


>>> x=1
>>> scope = VARs ()
>>> scope[' x ']
1
>>> scope[' x '] + = 1
>>> x
2


This invisible dictionary is called namespace or scope. In addition to the global scope, each function call creates a new scope.
Generally learned programming basic know what is the scope, here is not detailed.

Four. Recursion
The definition of recursion includes references to their own defined content.
A useful recursive function consists of the following parts:
(1) There is a basic instance when the function returns the value directly (minimum possibility problem)
(2) Recursive instances, including one or more of the most problematic recursive calls.
The key here is to break the problem down into small pieces, and the recursion cannot go on forever, because it always ends with the smallest possible problem, which is stored in the base instance.
Let's take 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 CodeThe code is 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 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)
  • 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.