Day4 - 函数、方法
函数作用提高代码复用性,简化代码
一、定义函数和调用
def hello():
print('Hello')
hello()
二、函数传参 - 必填参数
传递参数name、country,及需要传参的函数调用
def welcome(name,country):
print("welcome %s ,you are from %s" % (name,country))
return name,country
welcome("xiaohei","日本")
[result~]:
welcome xiaohei ,you are from 日本
三、函数所传递参数带有默认值 - 默认值参数
def welcome(name,country="北京"):
print("welcome %s ,you are from %s" % (name,country))
welcome("大美")
[result~]:
welcome 大美 ,you are from 北京
四、可选参数(参数值),不限制参数个数
接受到的结果会生成一个元组
def send_sms(*args):
print(args)
print("不传参数:%s" % send_sms())
print("传一个参数:%s" % send_sms(123))
print("传多个参数:%s" % send_sms(123,456))
[result~]:
()
不传参数:None
(123,)
传一个参数:None
(123, 456)
传多个参数:None
五、关键字参数,不限制参数个数
接受到的结果会生成一个元组
def send_sms(**kwargs):
print(kwargs)
send_sms(a=1,b=2,c="nnnn")
[result~]:
{'a': 1, 'b': 2, 'c': 'nnnn'}
六、调用函数时函数传参"*“和”**"区别:
a、调用函数时写两个**会将字典自动解开,转换为xx=xx,xx=xx格式,此例中会将函数传参改为add(a=13,b=2)格式,注意:形参名必须和字典中的key一样
b、调用函数时写一个*会将list解开,list中的元素必须和需要穿的参数个数一致
def add(a,b):
return a+b
d = {"a":13,"b":2}
result = add(**d) #调用函数时写两个**会将字典自动解开,转换为xx=xx,xx=xx格式,此例中会将函数传参改为add(a=13,b=2)格式,注意:形参名必须和字典中的key一样
print(result)
d = [1,2]
print(add(*d)) #调用函数时写一个*会将list解开,list中的元素必须和需要穿的参数个数一致
[result~]:
15
3
七、带有返回值的函数
a、函数里面定义的变量均为局部变量,只在函数内部生效
b、函数返回结果:
1)需要在函数中添加return结果
2)调用时要将函数return的结果保存在一个变量当中
3)函数中如果执行到return,则该函数会立刻停止
1.验证没有return时,返回结果为none
def welcome(name,country):
print("welcome %s ,you are from %s" % (name,country))
print(welcome("小黑","日本"))
[result~]:
welcome 小黑 ,you are from 日本
None
2.验证只有return,返回结果也是none
def test():
return
#content = test()
print(test())
[result~]:
None
3.验证return + 两个参数,返回值是一个元组
def welcome(name,country):
return name,country
print(welcome("小黑","日本"))
[result~]:
('小黑', '日本')
4.小练习:变更文件内容的函数:
def op_file(filename,content=None):
with open(filename,'a+',encoding="utf-8") as f:
f.seek(0)
if content:
f.write(content)
else:
result = f.read()
return result
word = op_file("student2.json")
print(word)
[result~]:
{
"code": 0,
"msg": "操作成功",
"token": "xxxxx",
"addr": "10.101.1.1",
"phone": "182026"
}
5.小练习:判断是否为小数
使用的字符串方法:
s.count(’.’) 判断字符串中’.‘的个数
s.split(’.’) 将字符串s以’.‘进行分割
s.isdigit() 判断s是否是一个数字
s.startwith(’-’) 判断字符串s是否以‘-’开头
s.strip() 去除s字符串的左右空格符
def is_float(s):
s = str(s)
if s.count('.') == 1:
left,right = s.split('.')
if left.isdigit() and right.isdigit():
return True
elif left.startswith('-') and left.count('-')==1 and left[1:].isdigit() and right.isdigit():
return True
else:
return False
else:
print(s.count('.'))
return False
price = input("请输入价格:".strip())
#result = is_float(price)
if is_float(price):
print("这是个小数")
else:
print("这不是个小数")
6.小练习:查看函数具体调用哪个参数
#查看函数具体调用哪个参数
money1 = 500
money2 = 400
def test(consume):
print("test 运行结果是:%s - %s" % (money1, consume))
return money1 - consume
def test1(money2):
print("test1 运行结果是:%s + %s" % (test(money2),money2))
return test(money2) + money2
money = test1(money2)
print(money)
[result~]:
test 运行结果是:500 - 400
test1 运行结果是:100 + 400
test 运行结果是:500 - 400
500
八、在函数中定义全局变量
如下标明全局变量和局部变量,
局部变量:
1)局部变量只对该函数起作用
2)如果需要将函数中的变量改为全局变量,需添加global a
3)未运行的函数不生效,故例2中在test函数中设置的全局变量a不生效
例1:
b = 100 #全局变量
def test():
# 在函数中设置全局变量,需要在变量前加global
# global a
a = 1 #局部变量
print(a)
test()
print(b)
例2:
def test():
global a
a = 5
def test1():
c = a + 5
return c
res = test1()
print(res)
九、递归函数
递归就是自己调用自己,并运行996次
#验证递归函数执行次数
count = 0
def test():
global count
count += 1
print("五一快乐",count)
test()
test()
递归就是一个循环,验证输入的数字是否为2的整数倍:
def test():
number = input("请输入一个数字:").strip()
number = int(number)
if number %2 ==0:
print("输入正确")
return
test()
test()