Functions and their parameters

Functions and their parameters

#_author: laitongxing 
#date: 2019/11/1
# Function
# 1 effect functions:
. # (1) reducing code duplication
. # (2) easy to modify, more scalable
. # (3) to maintain the consistency of the code
# 2 the function definition
# (. 1)
DEF F ():
Print ( 'OK')
F () # call must be added () OK
# (2)
DEF function (Number):
Print ( 'function% S'% Number)
function (. 1). 1 #function

# (. 3)
DEF the Add (A, B):
Print (A + B)
the Add (3,9) # 12 is
DEF A (B, A):
Print (A) # 2
Print (B ). 6 #
a (6,2)
. the arguments. 3 #
# (1) the parameters must
DEF print_info (name, Age):
Print ( 'the name:% S' name%)
Print ( 'Age:% D' Age% )
print_info ( 'Star', 22 is)
# (2) keyword parameters
print_info (Age = 23 is, name = 'Li')
print_info (name = 'Wei', Age = 23 is)
Print ( '----------------------' )
# (3) default parameter
def print_info1 (name, age, sex = 'male'): # default parameters with the other parameters of the back
( 'the name:% S' Print% name)
Print ( 'Age:% D'% Age )
Print ( 'Sex:% S' Sex%)
print_info1 ( 'Star', 22 is)
print_info1 ( 'Yu', 22 is, 'FEMALE')
Print ( '--------------- ------- ')
# (4) variable parameter
# location of the variable length parameter, args on the front, kwargs on the back
# (4-1) without named parameters
DEF F_ADD (* args):
Print ( args)
F_ADD (1,2) # (. 1, 2) args parameter is a tuple is a iterable
print ( '--------------------- - ')
DEF F_ADD (* args): # tuples traverse
SUM = 0
for I in args:
= i + sum
print (sum)
f_add(1,2,4,5,6,7,8)# 33
#(4-2)命名参数
def print_info1(*args,**kwargs):#
print(args)#('star', 22, 'male')
print(kwargs)# {'job': 'it', 'hobby': 'girls'}
print_info1('star',22,'male',job='it',hobby='girls')
print('----------------------')
def print_info2(**kwargs):
print(kwargs) # {'job': 'it', 'hobby': 'girls'}
for i in kwargs:
print('%s:%s'%(i,kwargs[i]))
print_info2(job='it',hobby='girls')
# job:it
# hobby:girls
print('----------------------')
def print_info3(sex='male',*args,**kwargs):# Default parameters on the front because the back two variable length parameters may be empty for i in kwargs: Print (kwargs) #
print (args) # If there is a default argument put leftmost


Print ( '% S:% S'% (I, kwargs [I]))
print_info3 ()
# ()
# {}
Print ( '------------------- --- ')
print_info3 (' FEMALE ', l, 2,3,) without printing FEMALE #
# (. 1, 2,. 3)
# {}
Print (' -------------- -------- ')
print_info3 (1,2,34,' FEMALE ')
# (2, 34 is,' FEMALE ')
# {}
# priority order parameter
#def function (name, sex =' male ', * args, ** kwargs)

Guess you like

Origin www.cnblogs.com/startl/p/11776157.html