python 函数,,函数,实现某些功能1


函数,实现某些功能

1、函数的定义:

def hello():

print("hello") #函数体

hello() #调用函数

函数必须被调用才会被执行

2、形参(函数中传入参数),实参(实际调用函数传入的参数)

def write_file(filename,content): #传入的参数是形参

  print(filename,content)

  with open(filename,‘a+‘,encoding=‘utf-8‘) as fw:

    fw.write(content)

#调用函数,函数的作用是往文件中写入内容

write_file(‘2.txt‘,‘123‘) #实参

write_file(‘1.txt‘,‘123‘)

#函数,读取文件中的内容

def read_file(filename):

  with open(filename,encoding=‘utf-8‘) as fr:

    content=fr.read()

    return content

res=read_file(‘1.txt‘)

print (res)

3、函数的返回值,在函数操作完成后,如果结果需要在后面的程序中用到,就需要return

函数中遇到return就立即结束

一个函数可以return多个值

4、def func(a,b):

    res=a+b

    print(res)

该函数无返回值,只能在函数里面使用res,不能在外面使用

def fun2(a,b):

  res=a+b

  return res

该函数有返回值,可以在函数外面直接使用return的值

比如:result=fun2(1,2)

print (result) #结果为3

5、一个函数可以return多个值

def get_user():

  s=‘abc,123‘

  user,password=s.split(‘,‘)

  return user,password

user=get_user()

print(user)

#函数可以返回多个值,用一个变量来接收时,把结果放在元组里面(‘abc’,‘123‘)

#在另外一个函数中使用这个函数

def login():

  username,password=get_user()

  user=input(‘wwe‘)

  password=input(‘wewe‘)

  if user==username and password==password:

    print(‘登录成功‘)

    return

  else:

    pass

6、

#默认值参数,不传就读取默认的,传了就用传了的,默认值参数写在最后面
def say(word=‘haha‘):
print(word)

say()
say(‘hheheh‘)

#通过判断content默认值参数,如果有值,就是写的操作,没有值,就是读的操作
def op_file(filename,content=None):
with open(filename,‘a+‘,encoding=‘utf-8‘) as fw:
fw.seek(0)
if content:
fw.write(content)
else:
res=fw.read()
return res

  

python 函数

评论关闭