Python code learning -- functions and built-in functions

Keywords: Python less Java

python code learning -- functions and built-in functions

function

Function definition: a piece of code that can realize a certain function
For example:
Common functions: len, range, print, input, int, str, list
append, pop, insert in the list
replace, strip, find, split in string
All of the above are built-in functions, i.e. python's own functions, which can be used directly
For example:

s = "I love Tiananmen in Beijing. The sun rises on Tiananmen"
print (len(s))

Syntax of functions

1. Keyword: DEF is used to determine whether it is a function in def python, so def cannot be used as a keyword
2. format:

    def function name (parameter 1, parameter 2, parameter 3 ):
  			Function body (note that there are colons for indentation and subcodes)
            Number of return variables

3. Note: the number of parameters in parentheses of function name can have 0 or more parameters. Parameter types are also divided into location parameter, default parameter, dynamic parameter and keyword parameter
4. The number of return variables can be 0 or multiple
Example:

#Write and call the first function, when the number of parameters in parentheses of function name is 0
def greet_hello():
    print("Good afternoon, everyone!!")
    return #After return, you can add variable or not

for i in range(0,10):
    greet_hello()#Calling function

Parameters of function

Parameter / position parameter

  1. The most common parameter in parentheses is a formal parameter, also known as a positional parameter
  2. Parameter represents that when calling a function, you must pass in a parameter. If you do not pass a parameter, the following error will be reported

    3. By using parameters, the diversity of code can be realized and the reusability of code can be improved, such as the following code:
    4. After defining the parameter, it is not necessary to use it, but it is necessary to pass the parameter
    5. There are several parameters in the parentheses of the function body. When calling a function, you must pass several parameters, which is a one-to-one relationship
def greet_hello(name,content,age):#Three parameters are defined
    print("{0},{1}Good!!".format(name,content))#Two used, one not used
    return

greet_hello("LEO","Morning",18)#Multiple parameters must be passed
greet_hello("Ella","Night",19)

Default parameters

Default parameter: there is a default value for the parameter. You can put both the parameter and the result of the parameter in the parameter list. When calling the parameter, the default parameter can not be passed
Note: 1) the default value of the default parameter must be placed after the location parameter. If it is placed before the location parameter, an error will be reported
2) There can be multiple default parameters
3) If the parameter is passed to the default parameter, the runtime displays the result according to the value of the parameter
4) By default, parameters are assigned in order. If you want to disturb the order of parameters when you transfer parameters, you can specify keywords when you call parameters, but the specified keywords must be consistent with the parameter name. When you specify keywords, keyword parameters must follow the parameters that do not specify keywords
For example:

def greet_hello(name,content,age='18'):#Three parameters are defined
    print("{0},{1}Good!!{2}Happy birthday".format(name,content,age))#Two used, one not used
    return

greet_hello("LEO","Morning")#Multiple parameters must be passed
greet_hello("Ella","Night")
greet_hello("habe","Morning",'22')#Default parameter transfer
greet_hello(content="habe",name='22',age="Morning")#assign key words
greet_hello("habe",content='22',age="Morning")#Specify keywords for some parameters

Use of return

1.return function: when a function is called, a result is returned to the function. Return also means that the function terminates. That is to say, the function body code after return will not be executed
For example, the following screenshot:

2. The results returned after return can be one or more. Multiple results can be separated by commas. If multiple results are returned, the returned format is tuple. If there is no returned result after return, the returned result is None. If there is no return in the function, python will add a return in the function by default, but the return value of return is None. Therefore, in the function Return no return value is the same as the return result without return in the function

def greet_hello(name, content, age='18'):  # Three parameters are defined
    print("{0},{1}Good!!{2}Happy birthday".format(name, content, age))
    return 'yezi'
def greet_say(name, content, age='18'):  # Three parameters are defined
    print("{0},{1}Good!!{2}Happy birthday".format(name, content, age))
    return 7,8
def greet_by(name, content, age='18'):  # Three parameters are defined
    print("{0},{1}Good!!{2}Happy birthday".format(name, content, age))
    return
m = greet_hello("LEO", "Morning")  # Multiple parameters must be passed
n = greet_say("meimei", "Noon")  # Multiple parameters must be passed
x = greet_by("lilei", "Noon", '20')  # Multiple parameters must be passed
print("return Return a single result{}".format(m))
print("return Return multiple results{}".format(n))
print("return No result returned{}".format(x))

Question: when do you want to return?
Answer: if you want to use the return value of this function to do other operations (further processing), you can use return to return results, for example: exercise questions

Exercise questions:
Write a function to calculate the integer sum of 1-100, and return the final result value

def number(x,y):
    count = 0
    for i in range(x,y):
        count += i
    return count

sum = number(1,101)
sum_1=number(1,101)+100#Add the returned result, so return returns
print("1-100 The sum is:{0}".format(sum))
print("sum_1 The result is{0}".format(sum_1))


Point: how to write a very useful function
A: three steps:
1) Write out the function with code first, or even use a set of data instead of parameters to see if the code is correct
2) Add def keyword and indent to turn code into function
3) Try to improve the reusability of code

dynamic parameter

1. Dynamic parameter also known as: indefinite length parameter, that is, you can input several parameters if you want to input several parameters, and the number of kettles generated can be: 0,1,2,3
2. Format of dynamic parameter: * variable name. In general, the variable name of dynamic parameter is args
3. The parameters input in the dynamic parameters will be output in the form of tuples when they are printed out

def coding(*args):
    #This is a function of a dynamic parameter
    print(args)
    return 3
t = coding("python","java","C#","C++","C","web")
print(t)

Key parameters

1. General writing method of keyword parameter: * * kwargs, the format of keyword parameter is: dual model + rename
2. The output format of key parameter is Dictionary
3. Keyword parameter supports any multiple keywords

def student_info(**kwargs):
    print(kwargs)

student_info(name = '33',age =18,clas= 'python12')

Mixed use of function parameters

When mixing parameters, pay attention to the order. The order is:
1. The default parameter must be placed after the position parameter
2. If you want to specify a keyword for the default parameter, the specified keyword parameter must be placed after the dynamic parameter
3. In general, the order of function parameters is: location, default, dynamic, keyword

def print_msg(a,b=10,*args):
    print('a',a)
    print('b',b
    print('args',args)

def print_msg_1(a,*args,b=10):
    print('a',a)
    print('b',b)
    print('args',args)

print_msg(1,2,3,4,5,6,7,8)
print_msg_1(1,2,3,4,5,6,7,8)

Exercises

1: A football team is looking for girls (both x and y) aged from x to y to join. Write a program to ask the user's gender (m for male, f for female) and age, then display a message to indicate whether the person can join the team, ask k times, and output the total number of qualified people.

def select_girl(k,x,y):
    count = 0#Define count to count the total number of people joining the football team
    for k in range(0,k):#Use for loop to control statistics
        sex = input("Please enter your gender")#Asking about sex
        if sex == "f":#Judge whether the gender is female
            age = int(input("Please enter your age"))#If it's a girl, ask age
            if x <= age <= y:#Judge whether the age meets the requirements
                count += 1#Age appropriate, stat + 1
                print("Congratulations, you can join the football team")#Print information that can be added to the football team
            else:#The age does not meet the requirements, print the information that cannot join the football team
                print("Your age does not meet the requirements. You cannot join the football team")
        else:#Information that the gender does not match, playing voice cannot join the football team
            print("Your gender does not meet the requirements. You cannot join the football team")
    print("Share{0}People join the football team".format(count))#Print how many people join the football team

select_girl(3,12,18)#Calling function


2: Write function, judge whether the length of the object (string, list, tuple) passed in by the user is greater than 5.6, write function, check the length of the incoming list, if it is greater than 2, only the first two lengths of content will be retained, and the new content will be returned

def LenText(f):
    if  len(f) > 5:
        print("Input is greater than 5")
    elif len(f) >6:
        print("Input is greater than 6")
    else:
        print('Input less than 5,6')

def LenList(input_list):
    if len(input_list)>2:#Determine whether the output list parameter is greater than 2
        input_list = input_list[0:2]#If greater than 2, the first two values of the slice form a new list
        return input_list#Return list
    else:
        print("The length of the list entered is less than 2")
LenText([1,2,"python",'123',{'namw':'yezi'}])
t =LenList([1,"python",'123',{'namw':'yezi'}])
n =LenList([{'namw':'yezi'}])
print("return The return value is{0},{1}".format(t,n))


3. Define a function, pass in a dictionary and string, judge whether the string is the value in the dictionary, if the string is not in the dictionary, add it to the dictionary, and return a new dictionary.

def new_dict(str_1,dict_1):
    if str_1 in dict_1.keys():
        print('The value in the string is the value in the dictionary key')
    else:
        if str_1 in dict_1.values():
            print('The value in the string is the value in the dictionary value')
        else:
            dict_1[str_1] = str_1
    return dict_1
new_dict('yezi',{'name':'yezi'})
new_dict('yezi',{'yezi':'name'})
t=new_dict('haha',{'name':'yezi'})
print(t)

Function calls to each other

The mutual invocation of functions is to call another function in one function, for example.

def print_msg(content):
    print('I want to say:{0}'.format(content))

def learn_language(name):
    print("I am learning.{}language".format(name))
    # Calling another function in a function is "hard" to be the value of content.
    print_msg('very difficult')

learn_language('English?')

def print_msg(content):
    print('I want to say:{0}'.format(content))

def learn_language(name,content):
    print("I am learning.{}language".format(name))
    # Calling another function in a function is "hard" to be the value of content.
    #print_msg('hard ')
    print_msg(content)#Parameterize the parameters of the called function on call

learn_language('Python','So hard')


Note:
**The execution of python language is top-down. If the calling function is placed between two functions, an error will be reported. * * for example, the following screenshot

Local variable, global variable and global

The difference between a local variable and a global variable is: scope (only works in one place)
Global variables: all applicable
Local variable: only available in one place

a=5#Global variables, outside the function, take effect in the module (py file)
def add(b):
    #addition
    a=6#Local variable, in a function, only works in the current function
    print(a+b)
def sub(b):
    #subtraction   
    print(b)
add(10)#a uses local variable 6
sub(5)#a uses the global variable 5

The law of global variables:
1. If there is no local variable inside the function, the global variable will be used
2. When the global variable and the local variable have the same name, the function takes priority to use its own local variable
3. When there is global in the function, the local variable in the function can be changed into the global variable in the module. That is to say, if the global variable is declared inside the function, we can change the value of the global variable inside the function, and it will take effect globally

Question: when to use global variables?
If A parameter A is A global variable, but function C needs to use parameter A processed by function B, then global is used to declare the local variable in the function as A global variable

in general:
The global variable acts on the whole module (py file), and the local variable acts on the inside of the function. If global is used to declare the local variable as a global variable within the function, the value of the global variable can be modified inside the function

Published 5 original articles, won praise 1, visited 303
Private letter follow

Posted by jonathandg on Tue, 28 Jan 2020 20:10:50 -0800