Python python learning function

Python functions

# Encapsulation function codes, reuse

The mathematical definition of y = f (x), y is a function of x, x is the independent variable. y = f (x0, x1, ..., xn)

Python functions

1, a block statement, the function name, the list of parameters configured by a number of statements, which is a minimum unit of an organization code

2, complete certain functions

Function returns

1, the basic structure of a package of programming code, according to the general functional organization of a code

2, the package for the purpose of reuse, to reduce the redundant code

3, code more simple and beautiful, readable and understandable

Classification function

1, built-in functions, such as max (), reversed (), etc.

2, library functions, such as Math.ceil (), etc.

3, custom functions, defined using the keyword def

Function definition
def function name (parameter list): # function name is an identifier 
function body (block) must be indented #
[return Return Value] # If no return, in fact return None

Function name is an identifier, as in claim named statement blocks must be indented, four spaces agreed functions Python if there is no return statement, implicitly returns a value of None parameter list is called the formal parameters defined, the expression of only a symbol ( identifier), referred to as parameter

Function call

Function definition, just declares a function that can not be executed, you need to call to perform the way the call is put parentheses after the function name, if necessary, to fill in the brackets on the parameters written in the call parameter is the actual parameter is incoming real value, referred to as the argument

def add (x, y): # function definition 
result = x + y # function body
return result # Return value out = (4,5) # function call add, there may be a return value, the return value received using the variable, 4 5 is an argument print (out) # print function is invoked parentheses


The above Code explanation: 1, define a function add, and the function name is add, to accept two parameters 2, the result of the calculation of a function, the return value returned required return statement 3, when invoked by the function name add plus 2 arguments, return values may be received using the variable.

4, the function name is an identifier, the return value is the value

5, the definition of need before calling, when that is called, has been defined, otherwise throw an exception NameError 6, the object function is callable, callable () Check out this function is not universal? Experience the benefits of function

Function Arguments

In the definition of the function is to form good agreement parameters, the actual parameters to provide sufficient call, generally, the number of formal and actual parameters to be consistent (except variable parameter).

Parameter passing mode

1, the position parameter passing the definition def f (x, y, z ), using the call f (1, 3, 5) , defined by parameter passing arguments order 2, the keyword parameter passing the definition def f (x, y , Z), using the call f (x = 1, y = 3, z = 5), using the name parameter passed in by the arguments, if a parameter name, and then transmission parameters can define the order sequence different requirements positional parameters must be passed before the keyword arguments, the arguments are in the position corresponding to the position

def f(x, y, z):
pass

f(z=None, y=10, x=[1])
f((1,), z=6, y=4.1)
f(y=5, z=6, 2) # 错误传参
The default parameter values ​​(each parameter must be received parameters can, or else a syntax error)

The default value is also referred to as a default value, a function may be defined as a default value for a parameter to increase. Its role: the default value of the parameter can not pass enough arguments when, for no given parameter default values assigned to the parameters lot of time, does not require the user to enter all the parameters every time, simplified function calls

the Add DEF (. 4 X =, Y =. 5): 
return X + Y test call to add (), add (x = 5), add (y = 7), add (6, 10), add (6, y = . 7), the Add (X =. 5, Y =. 6), the Add (Y =. 5, X =. 6), the Add (X =. 5,. 6), the Add (Y =. 8,. 4), the Add (. 11, X = 20 is ) can thus defined def add (x, y = 5 ) that can lean back with equal sign or def add (x = 4, y )? This will complain





# Define a function login, the parameter name Host, Port, username, password 
DEF Login (Host = '127.0.0.1', Port = '8080', username = 'Wayne', password = 'magedu'):
Print ( '{ }: @ {} {} / {} '. the format (Host, Port, username, password)) Login () Login (' 127.0.0.1 ', 80,' Tom ',' Tom ') Login (' 127.0. 0.1 ', username =' the root ') Login (' localhost ', Port = 80, password =' COM ') Login (Port = 80, password =' magedu ', Host =' WWW ')





variable parameter

Demand: Write a function that can accumulate sum of the number of multiple

Option One

def sum (iterable): # iteration which should be the object of 
SUM = 0
for X in Iterable: SUM = X + return SUM print (SUM ([l, 3,5])) # inside iterables print ( sum (range (4)))




On embodiment, the incoming iterables, and accumulates each element. It may also be used to complete the above functions. 可变参数

Scheme II (variable parameter passing mode position parameter)

def sum(*nums):
sum = 0
for x in nums:
sum += x
return sum

print(sum(1, 3, 5))
print(sum(1, 2, 3))

1, variable position parameter a, parameter used before the * indicates the position parameter is a variable parameter, can accept multiple arguments B, it is collected into a tuple argument in the tissue

Note: The tuple is passed in order to maintain the order of the reference time.

2, keyword variable parameter used before ** indicates that the parameter is a variable parameter keyword parameter can accept multiple keyword parameter names and values collected argument of it, in the tissue into a dict

def showconfig(**kwargs):
for k,v in kwargs.items():
print('{}={}'.format(k,v), end=', ')

showconfig(host='127.0.0.1', port=8080, username='wayne', password='magedu')

Mixed use

It can be defined as the following ways? 
showconfig DEF (username, password, ** kwargs)
DEF showconfig (username, * args, ** kwargs)
DEF showconfig (username, password, kwargs **, * args) #?

Summary: There are variable positional parameters and keyword arguments variable variable position parameters used an asterisk * before the parameter variable keyword arguments with two asterisks ** before the formal parameter variable parameter and variable key position word parameters can collect a number of arguments, the position of the variable parameter a tuple formed was collected, the collection form a variable parameter keyword dict mix parameters, when the common parameters needs to be set before the parameter list, the parameter of the variable parameters to be put behind, a list of variable position parameters needed before a keyword to a variable parameter

Example of use

def fn(x, y, *args, **kwargs):
print(x, y, args, kwargs, sep='\n', end='\n\n')

fn(3, 5, 7, 9, 10, a=1, b='abc')
fn(3, 5)
fn(3, 5, 7)
fn(3, 5, a=1, b='abc')
fn(x=3, y=8, 7, 9, a=1, b='abc') # ?
fn(7, 9, y=5, x=3, a=1, b='abc') # ?

fn (x = 3, y = 8, 7, 9, a = 1, b = 'abc'), the wrong parameter must pass before the keyword parameter passing position fn (7, 9, y = 5, x = 3 , a = 1, b = ' abc'), 7 and 9 in the wrong position has been passed in accordance with the parameters, x = 3, y = 5 plots the parameter passing

keyword-only parameter

Look at the piece of code

def fn(*args, x, y, **kwargs):
print(x, y, args, kwargs, sep='\n', end='\n\n')

fn(3, 5) #
fn(3, 5, 7) #
fn(3, 5, a=1, b='abc') #
fn(3, 5, y=6, x=7, a=1, b='abc')

After Python3, added a keyword-only argument.

keyword-only parameters: Common parameters when the parameter definition, a * after the asterisk, or after a variable position parameters, appear, it is not the normal parameters, known as keyword-only parameter.

def fn(*args, x):
print(x, args, sep='\n', end='\n\n')

fn(3, 5) #
fn(3, 5, 7) #
fn(3, 5, x=7)

keyword-only argument, implying that this argument must be the keyword of mass participation. It is believed that the above example, args parameter variable position parameters has captured all positions, followed by the position variable x can not pass the incoming reference.

Thoughts: def fn (** kwargs, x) can do?

def fn(**kwargs, x):
print(x, kwargs, sep='\n', end='\n\n')

Direct grammar mistakes.

Can be considered, kwargs intercepts all keywords mass participation, even wrote x = 5, x is no chance to get this value, so this syntax does not exist.

keyword-only parameter another form

  • An asterisk after all the parameters have become common keyword-only argument.

def fn(*, x, y):
print(x, y)

fn(x=6, y=7)
fn(y=8, x=9)
Mixing parameters of use
# Variable position parameters, keyword-only parameter default values 
DEF Fn (* args, X =. 5):
Print (X)
Print (args) Fn () # equivalent to Fn (X =. 5) Fn (. 5 ) Fn (X =. 6) Fn (l, 2,3, X = 10)




# General parameters, variable position parameters, keyword-only parameter default values 
DEF Fn (Y, * args, X =. 5):
Print ( 'X = {}, Y = {}' the format (X, Y). )
Print (args) Fn () # Fn (. 5) Fn (. 5,. 6) Fn (X =. 6) # Fn (. 1, 2,. 3, X = 10) Fn (Y =. 17, 2,. 3, X 10 =) # Fn (. 1, 2,. 3 = Y, X = 10) #







# General parameters, a default value, the variable keyword parameter 
DEF Fn (X =. 5, kwargs **):
Print (. 'X = {}' the format (X))
Print (kwargs) Fn () Fn (. 5 ) Fn (X =. 6) Fn (= Y. 3, X = 10) Fn (. 3, Y = 10) Fn (= Y. 3, Z = 20 is)






Parameters rule

General Parameter List parameter order is: Common parameters, default parameters, variable position parameters, keyword-only parameter (available with default values), the keyword variable parameters. Note: The code should be easy to read, rather than embarrass someone please define the function arguments in writing habits

def fn(x, y, z=3, *arg, m=4, n, **kwargs):
print(x,y,z,m,n)
print(args)
print(kwargs)

def connect(host='localhost', port='3306', user='admin', password='admin', **kwargs):
print(host, port)
print(user, password)
print(kwargs)

connect(db='cmdb')
connect(host='192.168.1.123', db='cmdb')
connect(host='192.168.1.123', db='cmdb', password='mysql')

The most common parameters defined for the general parameters, a default value may not be provided, must be provided by the user. Note that these parameters of the order, the most commonly used to define the parameter names must be used in order to use, defined as a keyword-only parameters required to use the keyword pass argument if the function has many parameters, not specifically defined, you can use variable parameters . If you need to know the meaning of these parameters, use the keyword variable parameters collection

Parameters deconstruction
the Add DEF (X, Y): 
Print (X, Y)
return X + Y the Add (. 4,. 5) the Add ((. 4,. 5)) # T =. 4,. 5 the Add (T [0], T [. 1] ) the Add (T *) the Add (* (. 4,. 5)) the Add (* [. 4,. 5]) the Add (*. 4 {,}. 5) the Add (Range * (. 4,. 6)) the Add (* { 'A ': 10,' b ': 11}) # can do? add (** { 'a': 10, 'b': 11}) # OK? add (** { 'x': 100, 'y': 110}) # OK?













Deconstruction parameters: When providing arguments to the function can be used before or iterables * ** to deconstruct structure, which extracts all the elements function as arguments using a positional parameter passing * solution using Solution ** keyword parameter passing constituting the number of elements extracted from the request parameter and to match the

def add(*iterable):
result = 0
for x in iterable:
result += x
return result

add(1, 2, 3)
add(*[1, 3, 5])
add(*range(5))
Workshop

1, write a function capable of receiving at least two parameters, the minimum and maximum return

def select(x, y, *args):
print(x, y, args)
return max(x, y, *args), min(x, y, *args)

import random
print(*select(*[random.randint(10, 20) for i in range(random.randint(2, 10))]))
------------------------------------------------------
19 18 (16, 10, 11)
19 10

2, a complete function, can receive a plurality of input numbers, returns the maximum so far every time the minimum value.

def double_values():
  max_ = min_ = None
  while True:
      x = input('>>>')
      nums = [int(c) for c in x.replace(',', ' ').split()]
      if not nums:
          continue
      if max_ is None:
          max_ = min_ = nums[0]
      max_ = max(max_, *nums)
      min_ = min(min_, *nums)
      print(max_, min_)

double_values()
---------------------------------------------------------
>>>12,13
13 12
>>>12 34 56
56 12
>>>33 44 55 66
66 12
>>>

 

Guess you like

Origin www.cnblogs.com/adaxi/p/12132723.html