一、函数的调用
代码块一:
def hello():print('hello1')print('hello2')print('hello3')hello()
示例一及运行结果:
代码块二:
def qiuhe():num1 = 20num2 = 30result = num1 + num2print('%d + %d = %d' %(num1,num2,result))qiuhe()
示例二及运行结果:
代码块三:
def python():print('python')def westos():print('westos')westos()python()
示例三及运行结果:
代码块四:
def hello(a):print('hello',a)hello('laoli')hello('laowu')
示例四及运行结果:
二、函数的参数
1、位置参数
代码块:
#位置参数def studentInfo(name,age): ##安装位置传参print(name,age)studentInfo('westos',12)studentInfo(12,'westos')studentInfo(age=11,name='westos')
示例及运行结果:
2、默认参数
代码块:
默认参数def mypow(x,y=2):print(x**y)mypow(2,3)mypow(4,3)
示例及运行结果:
3、可变参数
代码块一:
#可变参数def mysum(*a):sum = 0for item in a:sum += itemprint(sum)# a = [1,2,3,4,5] mysum(1,2,3,4,5)
示例一及运行结果:
示例二及运行结果:
4、关键字参数
代码块:
#关键字参数def studentInfo(name,age,**kwargs):print(name,age)print(kwargs)print(studentInfo('westos','18',gender='female',hobbies=['coding','running']))
示例及运行结果:
三、函数的返回值
代码块:
def mypow(x,y=2):return x ** y,x + yprint('hello')print(mypow(3))a,b = mypow(3)print(a,b)
示例及运行结果:
四、变量的作用域
代码块:
a = 1print('out: ',id(a))def fun():# global aa = 5print('in: ',id(a))fun()print(a)print(id(a))
局部变量示例及运行结果:
全局变量示例及运行结果: