The meaning of the function
In order to avoid repeating the creation of wheels, functions appear, which is to encapsulate a specific function
def my_func(li): def defines the function for the keyword my_func the function name is named the same as the variable name
for i in li:
count+=1
return count return Assign the return value to the caller of the function. If there is no return value, the return value of the function caller is None. If there are multiple return values, the function call returns a tuple composed of multiple values.
my_func() execute function
function parameters
The parameters passed to the function are divided into two categories
def my_len(li): li here is the formal parameter
for i li:
count+=1
my_len ()
s='edeffaf'
print(my_len(s)) where s is the actual parameter
From the point of view of actual parameters, there are several characteristics
1. One-to-one correspondence of positional parameters. 2. One-to-one correspondence of keyword parameters. 3. Mixed transmission.
location parameter
def re(a,b,c):
print(a)
print(b)
print(c)
re(3,24,2)
keyword arguments
def re(a,b,c):
print(a)
print(b)
print(c)
re(b=24,a= 234,c = 2)
def compare(a,b):
return a if a>b else b
print(comapare(b = 300,a = 200))
Mixed parameter pass keyword parameter is always behind
def re(a,b,c,d,e):
print(a)
print(b)
print(c)
print(d)
print(e)
re(1,9,d=23,e=24,c = 2)
From the point of view of formal parameters, there are several features
1. The positional parameters correspond to one-to-one in order. 2. The default parameters are overwritten, otherwise they will not be overwritten. The default parameters are always passed after the
positional parameters .
def re(a,b,c):
print(a)
print(b)
print(c)
re(3,24,2)
Default parameter
def func(a,b=23):
print(a,b)
func(66)
def info(name,sex='男'):
with open ('name_list',encoding="utf-8",mode='a') as f1:
f1.write('{}\t{}\n'.format(name,sex))
while True:
name = input("请输入:男生以1开头").strip()
if '1' in name:
name = name[1:]
info(name)
else:
info(name,'女')