Explains the use of python parameters and scopes

  • 2020-04-02 13:14:17
  • OfStack

This article shows you how to organize statements into functions, and details the concepts of parameters and scope, as well as the concept of recursion and its use in programs.
1. Create function
A function is callable, it performs some behavior and returns a value. Define a function with def :(not all functions return something)

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 document a function to be understood, you can add comments (starting with #). Another way is to just write the string, which is stored as part of the function, which is called a docstring.

def square(x):
    ' To calculate x The square of '
    return x*x

The # docstring can be accessed as follows:
> > > Square. _doc_
'compute x squared'.

Two. Parameter magic
Functions are simple to use and not complicated to create, but the use of function arguments is sometimes mysterious.
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:

>>> def to_change(n):
    n = 's'
>>> name = 'b'
>>> to_change(name)
>>> name
'b'

Strings (and Numbers and tuples) are immutable, that is, cannot be modified. But when variable data structures such as lists are used as parameters, the parameters are changed.

>>> 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've used are called positional parameters. Sometimes the order of parameters is hard to remember. To make things easier, provide the names of the parameters:

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

This way, the order of the arguments doesn't matter at all, but the names of the arguments must correspond to the values.
The parameters provided in this way with the parameter name are called keyword parameters, and the main purpose is to specify the role of each parameter.
The best thing about keyword arguments is that you can provide default values for them in functions:
> > > Def hello(greeting = 'hello',name = 'world'):
              Print '% s, % name! '
When an argument has a default value, you don't have to supply the argument when it's called, you don't have to, you can supply some or all of the arguments.

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

2.3 collection parameters
If only the function could store more than one name, the user could give the function as many arguments as he wants, so we need to do this: give the function one argument when we define it, preceded by an asterisk.

>>> 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 the values in the same tuple, so to speak, collecting these "parameters from the rest" for reuse. If no collection element is provided, the parameter is an empty tuple ().
However, if we need to process the "collection" operation of keyword parameters, we need two asterisks "**" :

>>> 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
()
{}

Take a closer look at the above example. The first three parameters are fixed, the fourth parameter, pospar, is a location parameter that can collect multiple parameters, and the fifth parameter is a keyword parameter that can collect multiple keyword parameters. 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 you can do the opposite if you use * and **. (1) used when invoked

>>> def add(x,y):
    return x+y
>>> params =(1,2)
>>> add(*params)
3

(2) used in the definition

>>> def with_stars(**kds):
    print kds['name'],'is',kds['age'],'years old'
>>> args = {'name':'Mr.Gumby','age':42}    
>>> with_stars(**args)
Mr.Gumby is 42 years old
 

scope
After the x=1 assignment statement is executed, the name x references the value 1. It's like using a dictionary, the keys reference the values, and of course, the variables and their corresponding values use an 'invisible' dictionary. The built-in vars function returns this dictionary:

>>> 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.
Those of you who have learned programming in general know what scope is, so I won't go into it.

4. Recursion
The definition of recursion includes references to what they themselves define.
A useful recursive function consists of the following parts:
(1) when a function directly returns a value, there is a basic instance (minimum possibility problem)
(2) recursive instance, including one or more recursive calls to the smallest part of the problem.
The key here is to break the problem into small pieces. Recursion cannot go on forever, because it always ends up with the least likely problems, which are stored in the base instance.
Let's look at three classic examples of recursion:
A. factorial
> > > Def factorial (n) :
      If n = = 1:
              Return 1
      The else:
              Return n * factorial (n - 1)
[/ code]
B. power

>>> def power(x,n):
    if n == 0:
        return 1
    else:
        return x * power(x,n-1)

C. Binary lookup (assuming the number must be in the sequence sequence)

>>> 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 articles: