Python Beginner's Study manual----function

Source: Internet
Author: User

1. Introduction

A function is a program segment that is reused. They allow you to give a name to a statement, and then you can run the block of statements any number of times in your program using that name. This is called a call function. We have used many of the built-in functions, such as input () and range ().

2. Definition and invocation of functions

The function is defined by the def keyword. The DEF keyword is followed by the identifier name of a function followed by a pair of parentheses . Parentheses can include some variable names , which end with a colon . Next is a piece of statement, which is the function body.

Def sayhi (): <span style= "White-space:pre" ></span> #无参函数的定义 with no return value. The function will automatically return none. None is a special data type in Python that represents everything                                                        #没有, equivalent to NULL in C.    print ("Hello I am Wang Nima") <span style= "White-space:pre" ></span> #注意缩进sayHi () <span style= "White-space: Pre "></span> #函数调用
The output is:

>>> Hello, I'm Wang Nima.
Def squaresum (A, B): <span style= "White-space:pre" ></span> #带形参的函数定义 (A, B is a formal parameter)    c = a**2 + b**2                                     #a * * 2 represents the square return of a    c<span style= "White-space:pre" ></span> #将c的值返回, unlike Java, <span style= "color:# ff6666; " >python can return multiple values and return </span><pre name= "code" class= "Python" style= "Color:rgb (255, 102, 102) in tuples;" >
Print (Squaresum (3,2)) #函数调用 to bring the value 3,2 into the function
The output is:
13
2.1 Functions with default parameters we can add a default value to the parameter directly when we define the formal parameter. It is important to note that formal parameters with default valuesput it on the right .。 For example "Def say (message, times = 1):" is correct and "Def say (Times=1, message):" Is wrong!
DEF say (message, times = 1): Print ((message+ ") * times)         #字符串可以通过 + number connection say (' Hello ') Say (' World ', 3)
Output results
2.2 When a key parameter is assigned to a function, we can assign a parameter directly to it by the formal parameter name.
def func (A, b=2, c=3):    print (values of "A, B, and C respectively", A,b,c)    func (1,3) func (1, c=24) func (c=50, a=100)
Output
Values for a, B, and C are 1 3 3a, B, and C respectively, with values of 1 2 24a, B, and C respectively 100 2 50
The string that *2.3 the document string in the first logical line of the function is the document string for this function. Note that docstrings is also suitable for modules and classes (though not yet learned that ...). )。 The document string is primarily used to give a function a schematic.
Def sayhi (): "" "This function is Wang Nima seduce sister Greeting" "" #只能通过三引号的行出, with well number not "" "this clause is also not a function string!                          "" "Print (" Hello I am Wang Nima ") <span style=" White-space:pre "></span>sayhi () print (sayhi.__doc__) #函数名后不需要括号, both sides of Doc are double-underlined help (Sayhi) #<span style= "color: #ff0000;" > Built-in Help function is actually read doc</span>
Output
Hello, I'm Wang Nima. This function is Wang Nima seduce sister greeting, help on Function sayhi in module __main__:sayhi () This function is Wang Nima seduce sister greeting


3. Local variables defined inside a function are called local variables, regardless of how the values of local variables change within the function,does not affect theVariable with the same name outside of the function. That is, the variable name is local to the function. This is called the scope of the variable. The scope of all variables is the block where they are defined.
A = 1def Changenum (a):                               #整数变量传递给函数, the function operates on it, but the original integer variable a does not change.    A = a + 1    return Aprint ("function return value is", Changenum (a)) print ("A's value is", a)
Output Result:

The function returns a value of 2a to 1
4. Use the global statement if you want to be outside the function as adefined within a functionVariable is assigned, you have to passGlobalThe statement tells Python that the variable name is not local, but global.
def func ():    Global x    Print ("The value of x in the function is", x)    x = 2    return xx =                                              #在函数外为一个定义在函数内的变量赋值print (' x value is ', x) Print ("Function return value is", func ())
Output results
The value of X is 50 the value of x in the function is 50 and the return value of the function is 2.



Tip: 1. Pointer passing allows the function to change the value outside the function! ForBasic data TypesVariable is passed to the function, the function copies a new variable in memory todoes not affect the original variable。 (We call thisValue Passing)
But forList, the list is passed to the functionA pointer, the pointer points to the position of the sequence in memory, and the operation of the table in the function is performed in the original memory, therebyaffect the original variable。 (We call thisPointer passing)
b = [1,2,3]def changelist (b):                              #我们将一个表传递给函数, the function is manipulated and the original table B is changed.    b[0] = b[0] + 1    return Bprint ("function return value is", Changelist (b)) print (<span style= "font-family:arial, Helvetica, sans -serif; " > "B's value is", </span><span style= "font-family:arial, Helvetica, Sans-serif;" >B) </span>

Output Result:

The function return value is [2, 2, the value of 3]b is [2, 2, 3]
2.Python can return multiple values, in the form of tuples
Def idsave ():    a=input ("Name:")    B=input ("Age:")    C=input ("Gender:")    return A,b,cprint (Idsave ())
Output Result:
Name: Wang Nima Age: 12 Gender: Female (' Wang Nima ', ' 12 ', ' female ')
3. Formal parameters with default values we can add a default value to the parameter directly when we define the formal parameter. It is important to note that formal parameters with default valuesput it on the right .。


Python Beginner's Study manual----function

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.