Python training camp 45 days - Day04 (function)

Catalog

Python's learning has entered its fourth day. In the previous chapters, we have learned basic variable manipulation, branch structure and loop structure. So in this chapter, let's talk about functions in python.

1. Introduction of Functions

In the development program, if you need to call a piece of code many times, but in order to improve the efficiency of writing and code reusability, so the code blocks with independent functions are organized into a separate small module, which is the function.

In Python, def keywords can be used to define functions, and like variables, each function needs to declare a name that conforms to the naming specification. We can put the parameters we need to pass in parentheses after the function, and we can also return the call result by using return keyword when the result is executed.

 

Case study:

Let's look at a math problem first.

In fact, the above question is equivalent to dividing eight apples into four groups, each with at least one apple. The answer to this question comes to mind.

If we haven't learned the function, we can write it like this.

"""
//Input M and N to calculate C(M,N)
version:0.1
author:coke
"""
m = int(input('m='))
n = int(input('n='))
fm = 1
for x in range(1,m + 1):
    fm *= x
fn = 1
for y in range(1,n + 1):
    fn *= y
fmn = 1
for z in range(1,m - n + 1):
    fmn *= z
print(fm // fn // fmn)

 

You should find that we have written the similar for loop three times. Can we make an extract?

"""
//Using Functions to Find Distribution Schemes
version: 0.1
author: coke
"""
#-*- coding:utf-8 -*-
def factorial(num):
    """
        //Finding factorial
        : param num Nonnegative integer
        : return num factorial
    """
    result = 1
    for n in range(1, num + 1):
        result *= n
    return result

m = int(input("Please enter a number. m: "))
n = int(input("Please enter a number. n: "))
print(factorial(m)//factorial(n)//factorial(m-n))

 

2. Parameters of functions

Functions are "building blocks" of a code supported in most programming languages, but there are many differences between functions in Python and those in other languages. One of the significant differences is how Python handles function parameters. In Python, function parameters can have default values and support the use of variable parameters, so Python does not need to support overloading of functions like other languages. So when we define a function, we can use it in many different ways.

from random import randint
def roll_rice(n = 2):
    """
        :param n:Number of colors
        :return: n Number sum of chromatons
    """
    total = 0
    for _ in range(n):
        total += randint(1,6)
    return total
def add(a ,b = 0 ,c=0):
    return a + b + c


print(roll_rice(1))
print(roll_rice(1))
print(roll_rice(2))
print(roll_rice(2))
# When passing parameters, they can be passed out of the set order.
print(add(c=50, a=100, b=200))

We set default values for the parameters of the above two functions, which means that if we call a function without passing in the values of the corresponding parameters, we will use the default values of the parameters. So in the code above, we can call the add function in different ways, which is similar to functions in many other languages. The effect of overloading is consistent.

In fact, there is a better way to implement the add function, because we may add 0 or more parameters, and the specific parameters can be completely determined by the caller.

#-*-coding:utf-8-*-
# The * before the parameter name indicates that args is a variable parameter
# That is, when the add function is called, 0 or more parameters can be passed in.
def add(*args):
    total = 0
    argsType = type(args)
    print("args The type is:%s"%argsType)
    for val in args:
        total += val
    return total

print(add())
print(add(1))
print(add(1,2))
print(add(1,2,3))

 

3. Modules and Functions

For any programming language, naming identifiers such as variables and functions is a headache, because we will encounter the awkward situation of naming conflicts. The simplest scenario is to define two functions with the same name in the same. py file. Since Python does not have the concept of function overload, the later definition overrides the previous definition, which means that only one function with the same name actually exists.

"""
//Test code
version:0.1
author:coke
"""
def foo():
   print("hello-world")

def foo():
   print("world-hello")
#What does the following code output? Is it a bit confusing?
foo()

 

Of course, we can easily avoid this situation, but if a project is developed by a team of people working together, there may be multiple programmers in the team who define a function called foo, then how can we resolve this naming conflict? The answer is very simple. Each file in Python represents a module. We can have functions with the same name in different modules. When using functions, we can import the specified module through the import keyword to distinguish which foo function in which module we want to use. The code is as follows.

module1.py

def foo():
    print("hello-world")

module2.py

def foo():
    print("world-hello")

moduleTest1.py

import module1 as m1
import module2 as m2
#Output hello-world
m1.foo()
#Output world-hello
m2.foo()

 

But if the code is written as follows, then the program calls the last imported foo, because the latter imported foo overrides the previous imported foo.

moduleTest2.py

from module1 import foo
from module2 import foo

# Output goodbye, world!
foo()

 

It should be noted that if we import modules that have executable code in addition to defining functions, then the Python interpreter will execute the code when importing the module. In fact, we may not want to do so. So if we write the executable code in the module, it is better to use these executable generations. The code is placed in the condition shown below, so that unless the module is run directly, the code under the if condition will not be executed, because only the name of the module directly executed is'_main_'.

def foo():
   pass
def bar():
   pass

# _ Name_is an implicit variable in Python that represents the name of the module.
# Only modules directly executed by the python interpreter are named _main__
if __name__ == '__main__':
   print('call foo')
   foo()
   print("call bar")
   bar

 

4. Recursive function

Recursive function: If a function does not call other functions internally, but itself, it is a recursive function.

 

For example: let's calculate the factorial n! = 1 * 2 * 3 *... * n

Solution 1: Cyclic Solution

"""
while Cyclic factorial
version:0.1
author:coke
"""
# -*- coding:utf-8 -*-
def calNum(num):
    i = 1
    result = 1
    while i <= num:
        result *= i
        i += 1
    return result

total = calNum(4)
print(total)

 

Scheme 2: Recursive function

"""
while Cyclic factorial
version:0.1
author:coke
"""
# -*- coding:utf-8 -*-
def calNum(num):
    if num > 1:
        result = num * calNum(num - 1)
    else:
        result = 1
    return result

total = calNum(4)
print(total)

 

5. Anonymous functions

Small anonymous functions can be created with lambda keywords. This function is named after omitting the standard steps of declaring a function with def.

The grammar of lambda functions contains only one statement, as follows:

   lambda [arg1 [,arg2,.....argn]]:expression

 

1. Use anonymous functions to find the sum of two numbers (self-defined functions)

"""
//Anonymous Function Testing
version:0.1
author:coke
"""
def add(a,b):
    return a+b

result1 = add(1,6)
# Using lambda expressions
sum = lambda  x,y: x+y
result2 = sum(1,6)
print(result1)
print(result2)

 

2. Data sorting (as a parameter of built-in function)

"""
Sort anonymous functions as built-in functions
 The knowledge points about Dictionaries and lists will be discussed later.
version:0.1
author:coke
"""
stus = [
    {"name":"zhangsan", "age":18}, 
    {"name":"lisi", "age":19}, 
    {"name":"wangwu", "age":17}
]
stus.sort(key = lambda x:x['name'])
print(stus)

 

6. Multiple Return Values

Can a function in python return multiple return values?

"""
//Testing of Multiple Return Values
version:0.1
author:coke
"""
def cal(a,b):
    add = a+b
    mul = a*b
    return add,mul

result = cal(2,3)
print(result)

Output result

 

A function that returns multiple return values essentially takes advantage of the characteristics of tuples.

Note: About tuples, lists and dictionaries, we will talk about the knowledge points later. Here's a word first.

Keywords: Python Lambda Programming

Added by adunphy on Thu, 19 Sep 2019 14:44:02 +0300