python基础之函数
来源:互联网 发布:linux arp命令 编辑:程序博客网 时间:2024/05/01 07:36
一、函数定义,参数,以及返回值
def 函数名():
函数体
返回值:通过return函数
>>> def fun():>>> def add(a,b):print(a+b)>>> add(34,78)112>>> def add1(a,b):return a*b>>> add1(12,5)60>>>
print('第一个函数')>>> fun()第一个函数>>> def fun(name):print("第二个函数"+name)>>> fun(age)Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> fun(age)NameError: name 'age' is not defined>>> fun('age')第二个函数age二、函数文档>>> def fun(name):'函数定义过程的name是形参!'#因为表示一个形式,标志占据一个位置print('传递参数'+name+'是实参,有具体参数值')>>> fun('xiao')传递参数xiao是实参,有具体参数值>>> fun._doc_Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> fun._doc_>>> help(fun)Help on function fun in module __main__:fun(name) 函数定义过程的name是形参!关键参数
>>> fun(name='关键参数')传递参数关键参数是实参,有具体参数值>>>
收集参数:
参数前加*
>>> def test(*param):print("参数的长度是:",len(param))print("第一个参数是:",param[1])>>> test(1,2,3,4)参数的长度是: 4第一个参数是: 2>>>
>>> def test(*param):print("参数的长度是:",len(param))print("第一个参数是:",param[1])>>> test(1,2,3,4)参数的长度是: 4第一个参数是: 2>>> def test1(*param,exp)SyntaxError: invalid syntax>>> def test1(*param,exp):print("参数的长度是:",len(param))print("第一个参数是:",param[1])print('exp是:',exp)>>> test1(1,2.3,4,exp="普通参数")参数的长度是: 3第一个参数是: 2.3exp是: 普通参数>>>
函数与过程:函数有返回值,python中只有函数、、
全局变量和局部变量:
def discount(price,rate): final_price=price*rate return final_priceold_price=float(input("请输入原价:"))rate=float(input("请输入折扣率:"))new_price=discount(old_price,rate)print("打折后的价格:",new_price)
内嵌函数和闭包:>>> count=5#全局变量>>> def myfun():count=10#局部变量print(10)>>> myfun()10>>> print()countSyntaxError: invalid syntax>>> print(count)5>>>
全局变量用global申明:>>> def myfun():global countcount=10print(count)>>> nyfin()Traceback (most recent call last): File "<pyshell#63>", line 1, in <module> nyfin()NameError: name 'nyfin' is not defined>>> myfun()10>>> print(count)10>>> count=1>>> print(count)1>>> myfun(count)Traceback (most recent call last): File "<pyshell#69>", line 1, in <module> myfun(count)TypeError: myfun() takes 0 positional arguments but 1 was given>>> myfun()10>>>
阅读全文
0 0
- python基础之函数
- python基础之函数
- Python基础之函数
- python之函数基础
- Python之函数基础
- Python学习基础之函数
- python之函数基础篇
- python学习之函数基础
- python基础之函数详解
- Python基础之二函数
- python基础3之函数
- python基础之函数篇
- Python基础篇之函数
- python之函数基础篇2
- Python基础之四函数式编程
- python基础内容重新理解之函数
- Python基础学习之函数(1)
- python基础之三——函数
- insert into select 中使用序号
- SpringMvc 浅析
- SELinux app权限配置
- 通过某位置的经纬度获取周边百度地图POI的信息
- 笔记:菜鸟教程-JavaScript
- python基础之函数
- 封装ajax-2
- 小学科学实验
- XML简介
- Spring bean 作用域
- C++:string类型与char*类型转换方法
- Python 元组(Tuple)操作详解
- XMLHttpRequest 的readyState 对象以及关于请求头status 的含义
- Java提高篇——对象克隆(复制)