Getting Started with Python function [] | write and call functions, multi-valued, recursive functions, define the default parameter / variable parameter

1, call the function

Python built a lot of useful functions, we can be called directly.

To call a function, you need to know the name and function parameters, such as seeking absolute value function abs, it receives a parameter.

Directly from the official website of the Python view the document:

Line can also view the abs function by help (abs) help in an interactive command.

Calls the abs function:

>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34

When calling the function, if the number of parameters passed wrong, wrong TypeError will be reported, and Python will clearly tell you: abs () has one and only one parameter, but gives two:

>>> abs(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)

If the number of parameters passed is right, but the parameters can not be accepted by the type of function, also reported TypeError mistakes, and give an error message: str parameter type is wrong:

>>> abs('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

And comparison function cmp (x, y) takes two parameters, if x <y, returns -1 if x == y, returns 0 if x> y, returns 1:

>>> cmp(1, 2)
-1
>>> cmp(2, 1)
1
>>> cmp(3, 3)
0

Python built-in function further comprises a common data type conversion functions, such as int () function can be converted to other data types are integers:

>>> int('123')
123
>>> int(12.34)
12

str () function to convert other types str:

>>> str(123)
'123'
>>> str(1.23)
'1.23'


Task:
SUM () function accepts a list as a parameter and returns a list of all the elements combined. Please calculate

1*1 + 2*2 + 3*3 + … + 100*100。

Code:

L = []
x = 1
N = 100
while x <= N:
    L.append(x*x)
    x=x+1
print sum(L)

Here Insert Picture Description

2. Write a function

In Python,
to define a function to be used def statement sequentially write the function name, parentheses, brackets and colon parameters:
Then, write the function block body is in the retracted, the function returns the value returned by return statement.

We customize the absolute value of a my_abs function as an example:

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x

Please note that statements inside the function body at the time of execution,
once executed to return, the function implementation is completed, and the results returned.
Thus, the internal function is determined by the conditions and the cycle can achieve very complex logic.

If no return statement, the function will return the results of execution after completion, but the result is None.

  • return None can be abbreviated to return.


Task:
Define a square_of_sum function that takes a list, returns the square of each element in the list and.

Code:

def square_of_sum(L):
    return sum([i * i for i in L])

print square_of_sum([1, 2, 3, 4, 5])
print square_of_sum([-5, 0, 5, 15, 25])

Here Insert Picture Description



3, return multiple values

Functions can return multiple values ​​it? The answer is yes.

For example in the game often need to move from one point to another point coordinates are given, and the displacement angle can be calculated new coordinates:

# The Math package provides sin () and cos () function, we first use the import refer to it:

import math
def move(x, y, step, angle):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny

At the same time so that we can get the return value:

>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print x, y
151.961524227 70.0

But this is only an illusion, Python function returns a single value remains:

>>> r = move(100, 100, 60, math.pi / 6)
>>> print r
(151.96152422706632, 70.0)

Return result print with print, the original return value is a tuple!

However, in the grammar, it returns a tuple parentheses may be omitted, and a plurality of variables may simultaneously receive a tuple, corresponds to a value assigned by location, so that, Python's return multiple values ​​actually returns a tuple, but more convenient to write .


Task:
a quadratic equation is defined: ax² + bx + c = 0

Please write a function that returns a quadratic equation of the two solutions.

Note: Python math package provides the sqrt () function is used to calculate the square root.

Code:

import math

def quadratic_equation(a, b, c):
    d = b * b - 4 * a * c
    x1 = (-b +  math.sqrt(d))/(2*a)
    x2 = (-b - math.sqrt(d))/(2*a)
    return x1, x2
print quadratic_equation(2, 3, 0)
print quadratic_equation(1, -6, 5)

summary:

  • Defining a function, it is necessary to determine the function name and the number of parameters ;
  • If necessary, you can do checks on the data type of the parameter;
  • The functions that can be used at any time to return to return a function result;
  • When the function completes did not return statement, automatic return None.
  • Function can return multiple values ​​simultaneously, but in fact is a tuple.



4, recursive functions

Inside the function, you can call other functions. If a function calls itself within itself, this function is a recursive function.

For example, we compute the factorial of n = 1 * 2 * 3 * ... * n, represented by a function fact (n), it can be seen!:

fact (n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact (n-1) * n
Therefore, fact (n) can be expressed as n * fact (n-1) , n = 1, only require special handling.

So, fact (n) is written in a recursive way:

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)

The above is a recursive function. You can try:

>>> fact(1)
1
>>> fact(5)
120
>>> fact(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L

If we calculate the fact (5), you can be seen as a function of the definition calculated as follows:

===> fact(5)

===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

Advantage is to define a simple recursive function, clear logic. In theory, all recursive functions can be written in a circular fashion, but not as good as recursive loop logic is clear.

Recursive function needs to be taken to avoid stack overflow.
In the computer, the function call is achieved through the stack (Stack) This data structure, each time a function call into the stack a stack frame is increased by one, each time the function returns, the stack will be reduced one stack frame. As the stack size is not unlimited, so the number of recursive calls too, can cause a stack overflow. Try computing fact (10000).

task:

Tower of Hanoi mobile recursive function can also be seen.

We column number a, b, c, all discs from can be described as a go to c:

If a disc has only one, it can be moved directly to C;

If there are N a disk can be viewed as a there is a disc (chassis) + (N-1) th disk, first need to (N-1) th disk moves to B, then a is Finally, a disk is moved to c, b, then (N-1) th disk moves to c.

Please write a function, given input n, a, b, c, the step of moving the print:

move(n, a, b, c)

For example, input move (2, 'A', 'B', 'C'), to print out:

A --> B
A --> C
B --> C

Reference Code:

#-*- coding:utf-8 -*-
# move(n, a, b, c)表示的是有n个盘子在a柱子上,将要移到b柱子上面去
def move(n, a, b, c):
# 如果a柱子上面只有一个盘子,则直接移到c柱子上面去并输出路径,结束递归
    if n == 1:  
        print a, '-->', c
        return
# 表示的是将n-1的盘子从a柱子上面移到b柱子上面去
    move(n-1, a, c, b)
# 输出最下面个盘子移从a移到c的路径
    print a, '-->', c
# 将b柱子上面的n-1个盘子移动到c柱子上面
    move(n-1, b, a, c)

move(4, 'A', 'B', 'C')

Here Insert Picture Description



5, the definition of default parameters

Defined functions, you can also have default parameters.

For example Python comes int () function, in fact, there are two parameters, we can either pass a parameter, and can pass two parameters:

>>> int('123')
123
>>> int('123', 8)
83

int () is a function of the second parameter binary conversion, if not pass, the default decimal (base = 10), if passed, with the parameters passed on.

Visible, the role of the default parameter function is to simplify the call , you just need to have to pass in parameters. But when needed, they can pass additional parameters to override the default parameter values.

We define a function of N th power of x is:

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

Suppose the maximum number of squares calculation, we can change the default value of n is set to 2:

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

As a result, there is no need to calculate the square of the two arguments:

>>> power(5)
25

Since the function parameters matches left to right, so the default parameters can only be defined later required parameters:

# OK:
def fn1(a, b=1, c=2):
    pass
# Error:
def fn2(a=1, b):
    pass


task:

Define a greet () function, which contains a default parameter, if not passed, print 'Hello, world.', If passed, print 'Hello, xxx.'

code:

def greet(name='world'):
    print 'Hello,' + name + '.'

greet()
greet('Bart')

Here Insert Picture Description

6, the definition of a variable parameter

If you want a function can accept any number of parameters, we can define a variable parameter:

def fn(*args):
    print args

In front of the name of the variable parameters have a asterisk,
we can pass in 0, one or more parameters to the variable parameters:

>>> fn()
()
>>> fn('a')
('a',)
>>> fn('a', 'b')
('a', 'b')
>>> fn('a', 'b', 'c')
('a', 'b', 'c')

Variable parameter is not very mysterious, Python interpreter will pass a set of parameters passed to assembly into a tuple of variable parameters, therefore, within the function, the variable directly as a tuple args like.

The purpose of defining variable parameters but also to simplify the call. Suppose we want to calculate the average value of an arbitrary number, you can define a variable parameter:

def average(*args):

    ...

In this way, when you call, you can write:

>>> average()
0
>>> average(1, 2)
1.5
>>> average(1, 2, 2, 3, 4)
2.4

Task:
Please write average accepts variable parameters () function.

code:

def average(*args):
    sum = 0.0
    if len(args) == 0:
        return sum
    for x in args:
        sum = sum + x
    return sum / len(args)
print average()
print average(1, 2)
print average(1, 2, 2, 3, 4)

Here Insert Picture Description

Published 20 original articles · won praise 0 · Views 409

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/103976942