Basic knowledge of functions

 
 
#Definition and use of functions
#Definition and use of functions
#1. Function without parameters:
#Define the function, it will not be executed;
def hello():
    #function body
    print('hello')
#Call functions
hello()
print (len ('hello'))
#2. Functions with parameters
def fun1(name):
    #name='xijiao'
    #Variables when defining a function are called formal parameters, and their variable names can be arbitrarily started;
    print('hello %s'%(name))
fun1('xijiao') #The parameter when calling the function is called the actual parameter, and this parameter must exist.


#Function return value and return statement
#When calling a function, there is generally a return value; when there is no return value, the default return value in python is None
def hello():
    print('hello')
res=hello() #Assign the function call to a variable
print(res) # print the variable

def hello():
    #return returns an expression or variable
    return 'hello'
res=hello()
print(res)


Application of #return
#Randomly generate 20 student scores, and judge the grades of these 20 students' scores:
import random # Import the random module, which is a random generation tool
def level(score): #define the level function with parameter scores
    if 90<score<=100:
        return 'A' #return returns 'A'
    elif 80<score<=90:
        return 'B'
    elif 70<score<=80:
        return 'C'
    else:
        return 'D'
def main(): #Define the main function
    for i in range(20):
        score = random.randint(1,100) #Randomly generate 20 integer scores from 1-100
        print('The grade is %s: the level is %s'%(score,level(score)))
main() #Execute the main function

scores=[] # define an empty list
for i in range (20): #Randomly generate all grades
    scores.append(random.randint(1,100))
for score in scores: #judging the grade according to all the scores
    print('The grade is %s, the grade is %s'%(score,level(score)))

Explanation of #None:
# In C: boolean is true, false, but in python, boolean is true, false
#In general, when there is no return value, we can define it as None, or in C or java, null can be defined as null, nil, undefined
var = None
print(type(var))        #<class 'NoneType'>
a=print()
print(a) # print result is None
#When the function has a return value, you can assign the function to a variable:
m=max([1,2,3,4,5]) #Assign the maximum value of the list to m
print(m) # print result is 5

#When there are multiple return values
def fun(a):              #a=[1,34,56,24,99,76,4]
    #Receive a list, find the maximum, minimum and average value of the list
    max1=max(a)
    min1 = min (a)
    avg1 = sum (a) / len (a)
    #In a python function, only one value can be returned;
    #If you must return multiple values, then encapsulate the returned value as a tuple of data
    return max1,min1,avg1
variables=fun([1,34,56,24,99,76,4])
print(variables,type(variables)) #(99, 1, 42.0) <class 'tuple'>, whose type is a tuple

#Formal parameter - required parameter
def add(x,y,z): #Here x,y,z are formal parameters
    return x+y+z
print(add(3,4,5)) #And here 3,4,5 are the actual parameters, that is, x=3, y=4, z=5
#Formal parameters - default parameters
#If there is only one actual parameter, x=..., y=2
#If there are only two actual parameters, x=2, y=3
def mypow(x,y=2):
    return x**y
print(mypow(2)) #There is only one actual parameter, x=2, and the default parameter y=2, so 2**2=4
print(mypow(2,3)) # There are two actual parameters, x=2, y=3, and the print result is 2**3=8

#print built-in function, the default end='\n', wraps the line, of course, we can also specify the value of end
print('hello')
print('world')
print('hello',end=',')
print('world')

#Formal parameter -- variable parameter
#Variable parameters, *variable name;
#*args, args is essentially a tuple:
def mysum(*args):
    print(args,type(args))   #(1, 2, 3, 5, 4) <class 'tuple'>
    return sum(args)
print(mysum(1,2,3,5,4))

#If it already exists: list, but to take each element of the list as a parameter, you can directly unpack *li
li=range(1,11)
# li = (1,2,3)
# li = {1,2,3}
print(mysum(*li)) #*li takes each element in the list and turns it into a tuple type


#Formal parameters -- keyword parameters
#**kwargs keyword argument; the accepted kwargs is a dictionary type;
def fun(**kwargs):
    print(kwargs,type(kwargs)) #The print result is {'a': 1, 'b': 2} <class 'dict'>
fun(a=1,b=2) #The actual parameter should be a dictionary type
d={
    'a':1,
    'b':2
}
fun(**d)
#<div id=s_tabwidth=100height=200>Webpage</div>
def make_html(label,value,**kwargs): #(Required parameters, default parameters, keyword parameters)
    s='' #define an empty string
    for k,v in kwargs.items(): # Traverse the key-value values ​​in the keyword arguments
        s+='%s=%s'%(k,v) #Add the key-value value of the keyword parameter to the empty string
    html='<%s %s>%s</%s>'%(label,s,value,label)
    return html
print(make_html('div','网页',id='s_tab',width=100,height=200))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325774648&siteId=291194637