The required parameters of the function refer to the parameters that must be passed in when the function is called
import math
def cal(n):return n * n
var=cal(2)print(var) # 4
The above function is to calculate the square of a number, when you want to calculate n^3, n^4.... Only two required parameters can be passed in
def cal_update(n,m):returnint(math.pow(n,m))var=cal_update(2,4)print(var) # 16
However, if most of the cases are square calculations, then cal_updtae(n,2) will be troublesome every time, so the default parameters are introduced
Default parameters, the incoming parameters by default
def cal_update2(n,m=2):returnint(math.pow(n,m))var=cal_update2(3) #Just pass in one parameter, 2print is passed in by default(var) # 9
Content expansion:
Python python function parameter: mandatory parameter, default parameter code example:
import math
# Required parameters of the function
''' The required parameters of the function refer to the parameters that must be passed in when the function is called
'''
def cal(n):return n * n
var=cal(2)print(var) # 4'''The above function is to calculate the square of a number, when you want to calculate n^3, n^4....Only 2 required parameters can be passed in
'''
def cal_update(n,m):returnint(math.pow(n,m))var=cal_update(2,4)print(var) # 16'''However, if most of the cases are square calculations, then cal will be used every time_updtae(n,2)It will be very troublesome, so the default parameters are introduced
'''
# Default parameters of the function
''' Default parameters, the incoming parameters by default
'''
def cal_update2(n,m=2):returnint(math.pow(n,m))var=cal_update2(3) #Just pass in one parameter, 2print is passed in by default(var) # 9
def student(name,sex,city='shanghai',age='20'):print('name:', name)print('sex:', sex)print('city:', city)print('age:', age)student('chris','male')
# name: chris
# sex: male
# city: shanghai
# age:20'''The default parameter must be an immutable object, if it is a variable object, problems may occur
'''
def count(name=[]):
name.append('chris')print(name)return name
count(name=['sarah','Tom'])
# [' sarah','Tom','chris']count();
# [' chris']count()
# [' chris','chris']When I call this function again, the default parameter name is not[],But it was not emptied last time['chris']'''The default parameter is a variable. It has been calculated when the function is defined. If there is a change, it will point to the new address
'''
So far, this article on what are the mandatory parameters of python is introduced. For more related python mandatory parameters, please search for the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will get more Support ZaLou.Cn!
Recommended Posts