Learn Python variables and parameters from the old

  • 2020-04-02 14:15:00
  • OfStack

So what is the difference and connection between these two? I did a bit of Internet research and found many of the same terms, but only the following paragraph from the Microsoft site seems to be highly abstract and far-reaching. I take over, read read, whether to understand, although it is for VB, as inspired.


The difference between parameters and variables (Visual Basic) In most cases, the procedure must contain some information about the calling environment. Procedures that perform repetitive or Shared tasks use different information for each invocation. This information contains the variables, constants, and expressions passed to the procedure each time it is called. To pass this information to the procedure, the procedure first defines a parameter, and then the calling code passes an argument to the defined parameter. You can think of the parameter as a parking space and the argument as a car. Just as a parking space can hold different cars at different times, the calling code can pass different arguments to the same parameter each time it invokes the procedure. A parameter represents a value that the procedure expects you to pass when it is invoked. When you define Function or Sub For procedures, you need to specify a list of parameters in parentheses immediately following the name of the procedure. For each parameter, you can specify the name, the data type, and the incoming mechanism ( ByVal (Visual Basic) or ByRef (Visual Basic) ). You can also indicate that a parameter is optional. This means that the calling code does not have to pass its value. The name of each parameter can be used as a local variable within the procedure. Parameter names are used the same way as any other variable. The arguments represent the values passed to the procedure parameter when you invoke the procedure. The calling code provides parameters when the procedure is invoked. call Function or Sub For procedures, you need to include a list of arguments in parentheses that follow the name of the procedure. Each argument corresponds to the parameter in the same position in the list.
 
Unlike parameter definitions, arguments do not have names. Each argument is an expression that contains zero or more variables, constants, and text. The data type of the evaluated expression should generally match the data type defined for the corresponding parameter, and in any case, the expression value must be convertible to this parameter type.

If you have to read this quotation, found that there are several key words: parameters, variables, parameters, parameters. I was trying to figure out the parameters and variables, but two more things popped up, which made it even more confusing. Please be calm, originally this paragraph quotation is a bit redundant, but, the reason cited, is to let the column to broaden the horizon, in the programming industry, there are a lot of similar things. The next time you hear someone say this, don't be afraid. You've heard it yourself.

In Python, it's not that complicated.

After reading the confusing quotes above, look at the code below and you'll see.


>>> def add(x):     #x Is the parameter
...     a = 10      #a Is a variable
...     return a+x
...
>>> x = 3           #x It's a variable, but it's outside the function
>>> add(x)          # Here, x It's a parameter, but it's made up of the previous variable x Transfer object 3
13
>>> add(3)          # I've merged the above processes
13

  At this point, see whether a little clear. Of course, I expressed the wrong place or understand the wrong place, also please do not hesitate to give advice, small may bow to thank.

Global and local variables

Here's a piece of code, notice that there's a function funcx() that has a variable x=9 in it, and a variable x=2 in front of it


x = 2 def funcx():
    x = 9
    print "this x is in the funcx:-->",x funcx()
print "--------------------------"
print "this x is out of funcx:-->",x

  So what is the output of this code? Look:


this x is in the funcx:--> 9
--------------------------
this x is out of funcx:--> 2

  As can be seen from the output, funcx() is run, and the variable x in funcx() is output is x=9; Then execute the last line in the code, print "this x is out of funcx:-- > ", x

In particular, the first x is the output of the inner variable x; The last x outputs the variable x outside the function. These two variables don't affect each other, although they're both x's. From here, we can see that the two X's each play a role in their respective fields, so such a variable is called a local variable.

There is a local, there is the corresponding all, in Chinese, all variables, seems to have ambiguity, thanks to the rich Chinese, and then took a noun: global variable


x = 2
def funcx():
    global x
    x = 9
    print "this x is in the funcx:-->",x funcx()
    print "--------------------------"
    print "this x is out of funcx:-->",x

  The difference between the above two pieces of code is that the latter has an extra global x inside the function, which means that it declares that x is a global variable, which means that this x is the same as the x outside the function, and then changes the reference object of x to 9 by x=9. So, here's what happens.
This x is in the funcx:-- > 9
--------------------------
This x is out of funcx:-- > 9

  It's as if global variables are powerful enough to dominate the inside and outside of a function. However, it is important to note that this should be used with caution, as it tends to lead to variable clutter. Inside and outside are different, in the program must pay attention to.

You don't know the number of parameters

When designing a function, sometimes we can confirm the number of parameters, for example, a function that is used to calculate the area of a circle, the parameter it needs is the radius (PI r^2), and the parameter of this function is fixed.

However, the world is not always so simple, and not always so certain, but the world is always uncertain. If you understand quantum mechanics, which many people have never heard of, then you understand real uncertainty. Of course, you don't have to study quantum mechanics to realize that the world is full of uncertainty. Isn't it? Behind bad luck comes good luck. Isn't that uncertainty?

Since there's a lot of uncertainty, the number of arguments to the function, of course there's uncertainty, how does the function solve this problem? Python solves the uncertainty of the number of arguments in this way:


def add(x,*arg):
    print x         # Output parameters x The value of the
    result = x
    print arg       # Output through *arg Method to get the value
    for i in arg:
        result +=i
    return result print add(1,2,3,4,5,6,7,8,9)    # The number of arguments assigned to a function is more than that 2 a

  After running this code, the following results are obtained:
1                                             This is the first print in the body of the function, and the value of x is 1
2, 3, 4, 5, 6, 7, 8, 9
45                                           # final calculation

  The result of this output is pretty unuser-friendly, and if you don't follow the function, you don't know what you're printing on each line. Blame yourself.

As you can see from the above example, if too many parameters are entered, all the other parameters pass through the *arg, passing to the parameter (variable) arg in the form of tuples. Notice that I'm using an obscure term here: parameter (variable), which means that arg is an argument at the head of a function before the data is passed in, and a variable when it's used in a function statement. That is, in many cases, the parameters and variables in the function are not so much to distinguish between the true, as to know the object is through what channels, that thing to what target.

To make args more visible (the names can be different, but the symbols must be there), use the following simple function to demonstrate:


>>> def foo(*args):
...     print args      # Print the object from this parameter
...
>>> # The following demonstration passes in different values separately, through the parameter *args The result >>> foo(1,2,3)
(1, 2, 3) >>> foo("qiwsir","qiwsir.github.io","python")
('qiwsir', 'qiwsir.github.io', 'python') >>> foo("qiwsir",307,["qiwsir",2],{"name":"qiwsir","lang":"python"})
('qiwsir', 307, ['qiwsir', 2], {'lang': 'python', 'name': 'qiwsir'})

  Whatever it is, it's stuffed into a tuple.

In addition to receiving multiple values with *args, you can also receive values with **kargs, but this time it's a little different:


>>> def foo(**kargs):
...     print kargs
...
>>> foo(a=1,b=2,c=3)    # Notice how the assignment is done and the result is printed
{'a': 1, 'c': 3, 'b': 2}

  What happens if I use foo(1,2,3) again?


>>> foo(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 0 arguments (3 given)

  To see here may think, is not uncertainty? I don't know exactly how the parameters will be passed. That's easy to do.


>>> def foo(x,y,z,*args,**kargs):
...     print x  
...     print y
...     print z
...     print args
...     print kargs       
...
>>> foo('qiwsir',2,"python")
qiwsir
2
python
()
{}
>>> foo(1,2,3,4,5)
1
2
3
(4, 5)
{}
>>> foo(1,2,3,4,5,name="qiwsir")
1
2
3
(4, 5)
{'name': 'qiwsir'}

  That's good, and it's good enough to handle all kinds of parameter requirements.


Related articles: