python 函数的使用方法


all_users ={}
#函数名
def read_users(file_name):
# 函数体
with open('a.txt', 'r', encoding='utf-8') as fr:
for line in fr:
up = line.strip().split(',')
s_username = up[0]
s_pswd = up[1]
all_users[s_username] = s_pswd
read_users('a.txt')
print(all_users) #函数必须调用才能执行

def hello(name):
print('welcome %s'%name)
hello('lily')
hello('cici')

def post(*args): ####可变参数,也叫参数组,当参数不固定的时候用,只要前面加个(*)号就行
##################一个( * )接收到的是元组,两个( * )接收到的是字典
##########不是必填参数,它接收到的是一个元组,他把调用函数时传进去的每一个参数都放在元组里
print(args)
post('001','login','username') #运行结果('001', 'login', 'username')

def other(name, age,country='china',*args):
print(name)
print(age)
print(country)
print(args)

#other('wubing','999','US','hehe','beijing','changping',user ='niuhanyang') ####不能这么写可变变量



def keyword(**kwargs): ##############关键字参数 一个(*)接收到的是元组,两个(*)接收到的是字典
##################################关键字参数,接收的是一个字典,
print(kwargs)
print(keyword())##########返回None
keyword(name='wubing',age = 18)####接收到的是字典{'name': 'wubing', 'age': 18}

d = {'name': 'wubing', 'age': 18}
def keyword(**kwargs): ##############关键字参数调用的用xx==11,
###################################传入字典调用的时候就得写**{'name': 'wubing', 'age': 18}
print(kwargs)
print(keyword())##########返回None
keyword(**d)####接收到的是字典{'name': 'wubing', 'age': 18}


def other(name, age,country='china',*args,**kwargs): ######如果必填参数、默认值参数、可变参数和关键字参数要一起用,
##################### 必须按照必填参数、默认值参数、可变参数和关键字参数的顺序接收
pass

#####关键字参数的调用
def write(filemane,model,encoding,user,os,money,other):
print(filemane)
print(model)
print(encoding)
print(os)
print(money)
print(other)
write(os='Windows', user='wubing', model='w', encoding='utf-8',money=9999,other='xxxxx',filemane='a.txt') #############这种叫做关键字调用,参数比较多时或者需要时使用
#write('a.txt','w',money=99,os='windos') ####错误的参数传入方式,必填参数按顺序填入了,其他的参数也必须按顺序填入
#write(os='windos','a.txt') ####错误的参数传入方式,必填参数按顺序填入了,其他的参数也必须按顺序填入

def plus(a,b):
return a+b ###########1、函数遇到return后,立即结束这个函数
#############2、调用完函数后,返回计算的结果

score1 = 50
score2 = 10

def echo(sum):
print('总分是:%s'%sum)
res = plus(score1,score2)
echo(res)

#如果返回多个值,则把所有返回的值放在一个元组中

#1, 递归调用
#一个函数调用自己就是递归调用
count = 0
def test(): #######递归调用自己时,最多调用999次,所以用递归调用时,必须有一个结束条件,递归函数效率不高
global count
count +=1
num = int(input('enput a number'))
if num%2 == 0:
return True
print('不是偶数,重新输入!')
test()
test()
#2,高阶函数
#如果一个函数的入参是函数名,则它是高阶函数
#函数既变量
def hello(name):
print(name)
new_hello=hello ### hello和newhello指向的同一个内存地址,所以他们两个是一样的
hello('14:30')
print(new_hello)
hello('hello...')
new_hello('new_hello...')

# 高阶函数例子
def add(x,y,z):
res = z(x)+z(y)
return res
print(add('98','100',int))

posted on 2017-06-04 16:32  yuer011  阅读(275)  评论(0编辑  收藏  举报

导航