函数
1、简单函数
(1)定义一个函数
(2)调用函数
2、函数的参数
(1)定义函数
(2)函数调用
3、多个参数的函数
(1)定义函数
(2)调用函数
4、函数返回值
(1)定义函数
(2)调用函数
5、函数参数---说明文档
(1)定义函数
(2)调用函数
(3)调用说明文档
6、关键字参数
(1)定义函数
(2)调用函数
7、默认参数
(1)定义函数
(2)调用函数
8、可变参数
(1)定义函数
(2)调用函数
9、返回多个值(实例1)
(1)定义函数
(2)调用函数
10、返回多个值(实例2)
(1)定义函数
(2)调用函数
11、变量作用域(实例1)
(1)test.py代码:
def discounts(price,rate):
final_price=price*rate
return final_price
old_price=float(input('please input the old price:'))
rate=float(input('please input the rate:'))
new_price=discounts(old_price,rate)
print('after discounts,the price is:',new_price)
(2)执行结果
12、变量作用域(实例2)
(1)test.py代码:
def discounts(price,rate): final_price=price*rate old_price=50 print('after modify the old_price1:',old_price) return final_price old_price=float(input('please input the old price:')) rate=float(input('please input the rate:')) new_price=discounts(old_price,rate) print('after modify the old_price2:',old_price) print('after discounts,the price is:',new_price)
(2)执行结果
13、变量作用域(实例2)
(1)代码及执行结果
count=5 def MyFun(): count=10 print(10) MyFun() print(count)
执行结果
(2)global关键字
代码及执行结果:
count=5
def MyFun():
global count
count=10
print(10)
MyFun()
print(count)
执行结果
14、闭包
一个闭包就是你调用了一个函数A,这个函数A返回了一个函数B给你。这个返回的函数B就叫做闭包。你在调用函数A的时候传递的参数就是自由变量
(1)定义
(2)调用