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 ofdefmultiple statements. When defining a function, we can define an explanatory document for the function in the following way.


Def square(x):
     'This is comment of this method !'
     Return x * x

#Get 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(greeting = 'Hello',name = 'world'):
    print('{},{}!'.format(greeting,name))

hello()
Hello,world!

hello(name = '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')
Testing

print_param(1,2,3)
(1,2,3) 





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(params)

print_dict(x = 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 + y


Param = (1,2) # Define a tuple as a parameter
Add(*param) # Use * to assign parameters
#Result is 3 , this is the result after assigning parameters 





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 inventedglobalto specify a value in a method as a global variable.


x = 1
Def change(x):
     Global x # The x at this point is pointing to the global variable x
     x = x + 1

Change(x)
At this time x = 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 aboven = 1 return 1two 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!) )


# Calculate the factorial of the number n n ! = n * (n-1) * (n -2) * ... * 1
#分析: The factorial of 1 is 1. The factorial of a number greater than 1 is equal to the factorial of n-1 * n
Def factorial(n):
     If n == 1 :
         Return 1
     Else :
         Return n * factorial(n-1) 





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


# Calculate the power of a certain number
  #Analysis: power(x,n) represents the power of x to be computed as n. That is, the number x is multiplied by n-1 times.
# For any number, when n is 0, the result is 1. When n > 0, power(x,n) = x * power(x,n-1), does it feel that you can do something with recursion? !
Def power(x,n):
     If n == 0 :
         Return 1
     Else :
         Return x * power(x,n-1) 





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 amap filter reducelook at some examples


# Using python recursive to achieve binary search
# Introduction: In the ordered list, the data to be compared is compared with the intermediate data. Split them in turn and compare the numbers in the middle.
Def search(list,number,lower,upper):
     'Use the dichotomy to find the index of the specified data, list is the sorted list, number is the searched data lower, upper specifies the starting position of the lookup'
     If lower == upper:
         Assertion number == list[upper]
         Return upper
     Else :
         Middle = (lower + upper) // 2 # // means no decimals except
         If number > list[middle] :
             Return search(list,number,middle+1,upper)
         Else :
             Return search(list,number,lower,middle) 





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.

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.