函数介绍
提高代码利用率,将重复执行的代码单独放在一块;
定义函数:首字母不能大写
def 函数名(): 代码
#定义函数: 1 def print_hell(): 2 print("hello,world") #执行函数 3 print_hell() [root@localhost python]# python3 25.py hello,world
函数中的参数:
[root@localhost python]# 1 def test1(r): 2 s=3.14*(r**22) 3 print("圆的面积为:%s"%s) 4 5 r=int(input("input r:")) 6 test1(r) 7 test1(3) #直接传参 [root@localhost python]# python3 26.py input r:3 圆的面积为:98536527172.26001 圆的面积为:98536527172.26001
函数中的多参数:
def 函数名(参数1,参数2 .......) #参数名可以随便写,在之前不需要定义,形参:特点不需要在前面定义,也不会和之前定义的变量冲突
1 a=1 2 def test2(a,b): 3 sum = a + b 4 print("%s+%s=%s"%(a,b,sum)) 5 b=2 6 test2(a,b) 7 test2(a,2)#在调用函数的时候传给函数参数的数据叫实参,20是实参,a=1为实参。实参可以引用定义的变量,也可以定义一个值 [root@localhost python]# python3 27.py 1+2=3 1+2=3
原文:https://www.cnblogs.com/zhaoyujiao/p/9032711.html