Functions in Python

Source: Internet
Author: User

Learn the data types in Python, the statements, then the functions in Python, functions are the core of structured programming. We use functions to increase the readability of the program. A custom function uses a keyword function that consists of def multiple statements. When defining a function, we can define an explanatory document for the function in the following way.

def Square (x):     ' This was comment of this method! '    return x * x#  Gets the method comment information Square. __doc__

The function defined above allows us to 函数名.__doc__ get the document string of the method in the same way.

In addition, all functions have a return value, and if you do not show what to tell it to return, then returnNone

How can a function less of the parameters of the part, a inattention may be mistaken, here is about to say, if the argument is an immutable parameter, it will not modify the value of the parameter, such as a number, string, tuple, but if the reference value, it may change the original value. Let's say a list, a dictionary. You can use slices to avoid changes to the incoming list, such as: change(names[:]) so we pass in a copy of the names list, and there is no effect on names itself.

Keyword parameters and default values, for example

def ' Hello ' '  World ' ):    print('{},{}! '  'YJK923') hello,yjk923!

Variable parameter: Allows the user to provide any number of parameters. The use * number collects all the supplied parameters into a tuple. This usage is also encountered when assigning a value. Example

def print_params (*param):    print(param) print_param ('testing  ') testingprint_param (all-in-a--)

The asterisk parameter is best placed at the end, otherwise you need to indicate the value of the parameter after the asterisk parameter when calling the method.
Another way to use two asterisks is to collect a method with a keyword parameter, and the resulting value is a dictionary instead of a tuple.

def print_dict (* *params)    :print= 1,y = 2,z = 3) {'Z  ':'3','x':'1  ','y':'2'}

All two of the above are used when defining a function, so we can use asterisks when we call a function, which is the allocation parameter, like this

def Add (x, y    ): return x +#  defines a tuple to use as a parameter #  to assign a parameter # The result is 3, This is the result after the allocation parameter

The concept of scopes in Python is similar to Java, so it's not a problem to understand, but Python doesn't seem to be honest, and we know that the variables in the method are local variables that are not affected by the global variables we use in the method, but Python The community's small partner is to change the value of global variables, how to do it? A keyword was invented global to specify a value in a method as a global variable.

x = 1def change (x):    Global#  at this point the X is pointing to the global variable x    x= x + 1 = 2

Recursion: The mutual invocation between functions is normal, there is a situation, that is to call themselves, this is recursive call.
Examples Show

# calculates the factorial n of the number n! = n * (n-1) * (n-2) * ... * 1#  Analysis: The factorial of 1 is 1, the factorial of a number greater than 1 is equal to the factorial of N-1 * ndef  factorial (n ):    if n = = 1        :return 1    else  :        return n * Factorial (n-1)

The recursive function usually contains two parts, one is the baseline condition, satisfies the condition function will put back a value directly, like the above n = 1 return 1 two is contains one or more calls, these calls is aimed at solves the problem the department. The key here is that by breaking the problem down into smaller departments, recursion can be avoided endlessly, because the problem will eventually be broken down into the smallest problem that the baseline condition can solve. (Abstract ah, look more, experience it!) )

# calculates the power of a number # Analysis: Power (X,n) represents the n-th power of the computed x. That is, the number x squared n-1 times.  # for any number, n is 0 when the result is 1,n > 0, Power (x,n) = x * Power (x,n-1), is not the feeling can be used to do something recursive!  def  Power (x,n):    if n = = 0        :return 1    Else  :        return x * Power (X,N-1)

Well, the above two recursive operations do not yet understand the concept of recursion, no matter, there is one!

#using Python recursion to find a binary method#Description: In an ordered list, you want to find the data and compare the intermediate data. Split in turn to compare the middle number. defSearch (list,number,lower,upper):'use the dichotomy to find the index of the specified data, list is a sorted listing, number is the data to find Lower,upper the starting position of the specified lookup'    ifLower = =Upper:assertNumber = =List[upper]returnUpperElse: Middle= (lower + upper)//2#//means not to leave decimals except        ifNumber >List[middle]:returnSearch (list,number,middle+1, Upper)Else :            returnSearch (List,number,lower,middle)

Having said so much, the understanding of functional programming is also so-so, using functions to write programs? You might see these functions provided in Python to deepen your sense of functional programming. Let's take a map filter reduce look at some examples

List (Map (Str,range (5)))#equivalent to [SRT (i) for I in range (5)]['0','1','2','3','4']#You can use filter to filter elements based on the return value of a Boolean function#first you have to have a function that returns a Boolean value.deffunc (x):returnX.isalnum ()#The Isalnum method detects whether a string consists of letters or numbersseq= ['Foo','x41','***','?!']list (Filter (FUNC,SEQ)) ['Foo','x41']#the same implementation can come in this way[x forXinchSeqifx.isalnum ()]#And a kind of thing called lambda expression, that's what it says.FilterLambdax:x.isalnum (), seq)#A lambda expression is an anonymous function, simple to understand, preceded by a colon, followed by a method body (return value) .LambdaX, Y:x + y#This is the anonymous function that indicates that there are two parameters and the return value is a parameter! #uses the specified function to set the first two elements of the sequence and two for one, and then the structure with the third element and two for one, and finally finishes processing the sequence to get a result. numbers = [72,42,7,9,23,67,97,245] fromFunctoolsImportReducereduce (Lambdax,y:x+y,numbers)#of course, in this case, you might as well use the built-in function sum sum. 

Well, the above is a function-related problem in Python, so far, we have learned the Python data types and data types of common operations, followed by statements, statements are involved in the use of some loops and conditional judgment statements, and functions can be regarded as a simple abstraction and encapsulation of statements, And the real object-oriented thinking is in the next section of the related concepts of the class.

Recommended reading:

Python Learning experience Sharing

Basic data types for getting started with Python

Statements in Python

Related Article

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.

Tags Index: