Basic Python Tutorial (vii)

Source: Internet
Author: User

This chapter describes how to organize statements into functions so that you can tell your computer how to do things.

Write a short code below to calculate the Gustav (the first two numbers and the third number)

Fibs = [0,1]   # defines a list, the initial content is 0,1for I in range (8):  #循环8次 fibs.append (fibs[-2]+fibs[-1])  #append在末尾追加一个数, This is its front two number and # input >>> fibs# output [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Since the assigned value fibs already has two numbers (0,1), after the Loop 8 times, the list has 10 numbers, and the two numbers are added equal to the 3rd number.

Do you think we should input to control the number of printing? Just change the program a little bit.

fibs = [0,1]num = input (' How many Fibonacci numbers does you want? ') For I in Range (num-2):    fibs.append (fibs[-2]+fibs[-1]) print fibs# input >>> How many Fibonacci numbers does you want ? 12# Output [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Abstract

Abstraction has the key to saving a lot of work, which makes it possible for a computer program to be readable. Computers like to handle precise and specific instructions, but unlike people, we prefer to throw in a thing, and the computer can give feedback to the results we want, rather than telling it how to do it step-by-step. So, the above code is a little abstract and should look like this:

num = input (' How many Fibonacci numbers does you want? ') Print fibs

How does the computer know what to do? We can encapsulate the process as a function, just call this function whenever we use it.

Create a function

A function can be called, which performs some behavior and returns a value. The built-in callable function can be used to determine whether a function can be called:

>>> import math>>> x = 1>>> y = math.sqrt>>> callable (x)  false>>> Callable (y) True

Note: Callable is no longer available in python3.0.

So how do you define a function? You can use the DEF statement to:

>>> def Hello (name):    return ' hello. ' +name+ '! ' #我们定义了一个hello函数, it adds "hello." Before the input. Back Add "! "and return to the # account >>> print hello (' world ') hello.world!>>> print hello (' Zhangsan ') hello.zhangsan!

That's good! Go back and think about how to define the return Gustav sequence as a function. As follows:

#定义fibs函数, for Gustav Sequence >>> def fibs (num):    result = [0,1] for I in    Range (num-2):        result.append (result[  -2]+RESULT[-1])    return result# call fibs function directly >>> fibs [0, 1, 1, 2, 3, 5, 8,, 34]>>> fibs (15) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Local variables

When a function defines a life variable, the variable within the function is only valid within its function and has no relation to other variables with the same name outside the function.

#局部变量def func (x):    print ' x is ', x    x =2    # x=2 only functions within the Func function    print ' Changed local x to ', x    x = 50func (x) 
    #func函数并没有返回数据过来. print ' x is still ', x# output >>> x is 50Changed local x to 2x is still 50

Global statement

If you want to make a variable global, you can use the global statement.

def func ():    Global x    print ' x is ', x    x = 2 "    print ' Changed local x to ', XX =50func ()" Print ' Value of x is ', x# Output x is 50Changed local x to 2Value of X is  2

The global statement is used to make life X global, so after the Func function is executed, the value of x has changed and is acting on the entire program, so the last input result is 2

Default parameters

For some parameters, we want some of its parameters to be optional, and if the user does not want to provide values for these parameters, these parameters will use the default values.

def say (Message,times=1):    print Message*timessay (' hello ') Say (' World ', 5) #输出 >>> Helloworldworldworldworldworld

The two parameters of the defined say function are optional, the default is Times=1; that is, the two parameters are multiplied by the output.

Note: Only those parameters at the end of the formal parameter list can have default parameters, such as Def func (A=5,b), which is not valid.

Key parameters

If a function has many parameters and we want to specify only a subset of them, you can use the first name (the keyword) instead of the location to assign the argument to the function. ----This is called the key parameter

def func (a,b=5,c=10):    print ' A is ', A, ' and B is ', B, ' and C is ', Cfunc (3,7) func (24,c=32) func (c=23,a=14)
#输出 >>> A is 3 and B are 7 and C is 10a are and B is 5 and C are 32a is and B are 5 and C is 23

In doing so, I don't have to worry about the order of the parameters, it's easier to use the function. Assuming that other functions have default values, we can assign values only to the parameters we want.

Recursion:

Useful recursive functions ... Wait, what is the useless recursion? Let's look at the definition of a function:

def recursion ()    return recursion ()

Obviously, it can do nothing, the execution of the program constantly apply for memory, direct memory exhaustion, program crashes.

Next, a useful recursive function consists of the following parts:

    • Basic instance (minimum likelihood problem) when function returns value directly
    • Recursive instances, including one or more recursive invocations of the least part of the problem.

The following is a recursive function to calculate an n order, n (n-1) * (n-2) *....*1

def f (n):    if n = = 1:       return 1    else:        return n*f (n-1)


Basic Python Tutorial (vii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.