This is the 9th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

preface

Now that you’ve learned about data types and statements in Python, let’s talk about functions in Python. Functions are at the heart of structured programming. We use functions to increase the readability of programs.

Custom function

The keyword def function is composed of multiple statements. When defining a function, we can use the following way to define an explanation document for the function.

def square(x): 'This is comment of this method ! 'return x * x # get method comment information square.__doc__Copy the code

For the function defined above, we can get the docstring of the method as the function name.__doc__.

Also, all functions return a value. If you don’t show it what to return, return None

If you pass an immutable parameter, you don’t change the value of the parameter, such as a number, string, or tuple. If you reference a value, you may change the value. Like lists, dictionaries. You can avoid changes to the passed list by slicing, such as change(names[:]), so that we pass in a copy of the names list without affecting the names themselves.

Parameters of a function

Keyword parameters and default values, for example

def hello(greeting = 'Hello',name = 'world'): print('{},{}! '.format(greeting,name)) hello() Hello,world! Hello (name = 'non-serious programmer ') Hello, non-serious programmerCopy the code

Variable parameters: Allows the user to provide any number of parameters. Collect all supplied parameters into a tuple using an * sign. This usage is also encountered in assignment. For example,

Def print_params(*param): print('Testing') print_param(1,2,3) (1,2,3)Copy the code

The asterisk argument is best left last, otherwise you need to specify the value of the argument after the asterisk argument when calling the method. Another method that uses two asterisks is for collecting arguments with keywords, yielding 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'}
Copy the code

We can also use an asterisk (*) when we call a function, which is to assign arguments, like this

Def add(*param) : return x + y param = (1,2) # def add(*param) : return x + y param = (1,2) #Copy the code

The global keyword

The concept of scope in Python is similar to Java, so it’s not a problem to understand, but Python doesn’t seem to be completely straightforward. We know that variables in methods are local variables, and when we use them in methods, global variables are not affected, but the Python community wants to change the value of global variables. How do you do that? The global keyword was invented to specify that the value in a method is a global variable.

X = 1 def change(x): global x = 1 def change(x): global x = 2Copy the code

Recursive function

Recursion: it is normal for functions to call each other, and there is a case where they call themselves. This is called recursion. For example

Calculate the number n factorial n! = n * (n-1) * (n -2) * ... Def factorial(n): if n == 1: return 1 else: return n * factorial(n-1)Copy the code

Recursive functions usually have two parts: one is the baseline condition, which will directly return a value, such as n = 1 return 1, and the other is one or more calls, which are intended to solve a part of the problem. The point here is that by breaking the problem down into smaller parts, you avoid endless recursion, because the problem will eventually be broken down into the smallest problem that the baseline condition can solve. (Abstract ah, look more, experience it!)

Analysis: Power (x,n) means to compute x to the NTH power. So you multiply x by itself n minus 1 times. Power (x,n) = x * power(x,n-1); def power(x,n): if n == 0 : return 1 else : return x * power(x,n-1)Copy the code

Well, the two recursion operations above don’t understand the concept of recursion, that’s ok, there’s one more!

Compare the data to the intermediate data in an ordered list. Divide it up and compare the middle numbers. def search(list,number,lower,upper): If lower == upper: if lower == upper: if lower == upper: Assert number == list[upper] return upper else: middle = (lower + upper) // 2 # // return search(list,number,middle+1,upper) else : return search(list,number,lower,middle)Copy the code

Having said all that, the understanding of functional programming is also sloppy, using functions to write programs? You may have seen a few functions provided in Python to get a feel for functional programming. Map Filter Reduce gives some examples

List (map(STR,range(5))) # is equivalent to [SRT (I) for I in range(5)] ['0','1','2','3','4'] # First you have to have a function def func(x) that returns a Boolean: Seq = ['foo','x41','***','?! '] list(filter(func,seq)) ['foo','x41'] # [x for x in seq if X. isalnum()] # Filter (lambda x: x.isalnum(),seq) # lambda is an anonymous function. The colon precedes the argument and the method body (return value) lambda x, y: X + y # this is an anonymous function that returns two arguments and. # add the first two elements of the sequence to one, then add the third element to one, and finally process the sequence to get a result. Numbers = [72,42,7,9,23,67,97,245] from functools import reduce reduce(lambda x,y:x+y,numbers) # Instead, use the built-in function sum.Copy the code

Ok, so that’s all about functions in Python. Now that we’ve looked at Python’s data types and the common operations they use, we’ve moved on to statements, which involve loops and conditional statements. Functions can be thought of as simple abstractions that encapsulate statements. The real idea of object orientation comes in the next section on concepts related to classes.