Python-custom function-parameters

First, the custom function parameters

1. Kind

(1) Position parameters

"x" is the positional parameter

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author: dingkai
#mtime: 2018/4/27

def power(x):
    result = x * x
    print(result)

(2) Default parameters

"n" is the default parameter

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author: dingkai
#mtime: 2018/4/27

def power(x,n=1):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

(3) Variable parameters

"numbers" is a variable parameter. When calling the calc function, the argument numbers is a list

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
     return sum
print(calc([1,2,3]))

(4) Keyword parameters

"**every" is a keyword argument

def person(name,age,**every):
print('name:',name, 'age:',age, 'other:', every)

extra = {'city':'Beijing', 'job':'OPS'}
#person('dingkai',25,city = extra['city'],job = extra['job'])
#person('dingkai',25,**extra)

(5) Named keyword arguments

After "*" is the naming keyword

def person(name,age,*,city,job):
    print(name,age,city,job)
#person('dinkai',26,city='Beijing',job='OPS')

 

 

 

2. Notes:

(1) The required parameters are in the front, and the default parameters are in the back, otherwise the Python interpreter will report an error (think about why the default parameters cannot be placed in front of the required parameters);

(2) is how to set the default parameters.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324989607&siteId=291194637