博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 函数
阅读量:4329 次
发布时间:2019-06-06

本文共 1526 字,大约阅读时间需要 5 分钟。

函数,实现某些功能

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

  

转载于:https://www.cnblogs.com/qiuqiu64/p/10060694.html

你可能感兴趣的文章
万方数据知识平台 TFHpple +Xpath解析
查看>>
Hive实现oracle的Minus函数
查看>>
秒杀多线程第四篇 一个经典的多线程同步问题
查看>>
RocketMQ配置
查看>>
vs code调试console程序报错--preLaunchTask“build”
查看>>
蚂蚁金服井贤栋:用技术联手金融机构,形成服务小微的生态合力
查看>>
端口号大全
查看>>
机器学习基石笔记2——在何时可以使用机器学习(2)
查看>>
POJ 3740 Easy Finding (DLX模板)
查看>>
MySQL 处理重复数据
查看>>
关于typedef的用法总结(转)
查看>>
【strtok()】——分割字符串
查看>>
Linux下安装rabbitmq
查看>>
曹德旺
查看>>
【转】判断点在多边形内(matlab)
查看>>
java基础之集合:List Set Map的概述以及使用场景
查看>>
Python 线程 进程 协程
查看>>
iOS语言中的KVO机制
查看>>
excel第一次打开报错 向程序发送命令时出错 多种解决办法含终极解决方法
查看>>
响应式web设计之CSS3 Media Queries
查看>>