1 函数:实现某个功能的一些代码
2
3 #定义函数
4 def hhh():
5 print('这是一个函数')
6 ---------------------------------------------------------------------------------------------------------
7 #调用函数
8 hhh()
9
10 ---------------------------------------------------------------------------------------------------------
11 def hhh():
12 pass #就是什么也不做的意思
13
14 ---------------------------------------------------------------------------------------------------------
15 def calc(a,b):#形参,形式参数
16 print(a,b)
17 return a+b #返回值
18
19 res = calc(1,2)#实参,实际参数
20 res 用来接收返回值
21 print(res)
22
23 ---------------------------------------------------------------------------------------------------------
24 #判断输入的是否是合法的小数
25 #1、判断是否只有一个小数点
26 #2、小数点左边的是一个整数,小数点右边的也是一个整数
27 #3、小数点右边的也是一个整数,左边要以负号开头,只有一个负号,负号后面是整数
28
29 # input("请输入价格:")
30
31 def check_float(num):
32 num = str(num)
33 if num.count('.')==1:
34 left,right = num.split('.')
35 if left.isdigit() and right.isdigit():
36 return True
37 elif left.starswith('-') and left[1:].isdigit()and right.isdigit():
38 return True
39 return False
40
41 print(check_float('1.2'))
函数参数
一、必填参数(位置参数)
def say_hello(word):
print(word)
二、默认值参数
def say_hello(word='hell0'):
print(word)
say_hello()
say_hello('hi')
运行结果:hell0
hi
------------------------------------------------------------------------------------------------------------
#一个函数实现两个功能,能读文件,也能写文件
方法一:
def op_file(file,content=None):
if content: #非空即真
f = open('file','w',encoding='utf-8')
# f.write(content)
json.dump(content,f)
else:
f = open(file,encoding='utf-8')
# res = f.read()
result = json.load(f)
-----------------------------------------------------------------------------------
方法二:
import json
def op_file(file,content=None):
if content: # 非空即真
with open(file,'w',encoding='utf-8') as f:
json.dump(content,f)
else:
with open(file,encoding='utf-8') as f:
return json.load(f)
----------------------------------------------------------------------------
三、参数组 【*args】
def send_mail(*name): #参数组 可以传一个,也可以传多个参数
print(name)
send_mail('bd')
#1.不传参数
#2.传1个
#3.传n个
#4.传过去的是一个什么东西 #多个参数放一个元组传给你
send_mail()
send_mail('ds')
send_mail('zz','xx','fd','we')
运行结果:('bd',) #元组只有一个元素的时候,后边加一个逗号
()
('ds',)
('zz', 'xx', 'fd', 'we')
--------------------------------------------------------------------------------------
四、关键字参数
def szz(name,age,sex,addr,phone,qq,mail):
print(name,age,sex)
szz(addr='beijing',qq=2343,mail='dfsd@164.com',name='abc',age=34,sex='df',phone=2343)
szz('xiaohei',18,addr='beijing',phone=234,mail='dfsd@164.com',qq=2343,sex='df')
#调用函数的时候,可以全部都用位置参数,位置参数是一一对应的,必须按照位置来传参
#也可以全部都用关键字参数,指定关键字,不需要按照顺序来
#也可以一起用,但是要先写位置参数,再写关键字参数,关键字后面参数不能再出现为止参数
运行结果:abc 34 df
xiaohei 18 df
-----------------------------------------------------------------------------------------------------
def xiaohei(**info):
print(info)
#1.参数是否必传 不是必填的
#2.位置参数传参,是否可以 ---不可以
#3.关键字参数传参是否可以 ---可以
#4.是否限制参数的个数 ---不限制
xiaohei()
# xiaohei(12,3,4) #报错
xiaohei(name='fdfs',addr='fadsfdf')
-----------------------------------------------------------------------------------------------------------
举例应用:
def xiaobai(name,age,*args,**kwargs):
print(name)
print(age)
print(args)
print(kwargs)
xiaobai('xiaobai',18,'beijing','shanghai',money
=500,func=2032)
运行结果:xiaobai
18
('beijing', 'shanghai')
{'money': 500, 'func': 2032}
----------------------------------------------------------------------------------------------------------------
def op_mysql(host,port,user,passwd,db):
print(host)
print(port)
print(user)
print(passwd)
print(db)
db_info = ('127.0.0.1',3306,'root','123456','szz')
op_mysql(*db_info) #代表拆开这个列表 #解包
#代表拆开这个列表 一一对应传参数,#有下标的都可以这么整
---------------------------------------------------------------------------------------------------
def op_mysql(host,port,user,passwd,db):
print(host)
print(port)
print(user)
print(passwd)
print(db)
db_info2 = {
'host':'127.0.0.1',
'port':3306,
'user':'szz',
'passwd':12322,
'db':'szz'
}
op_mysql(**db_info2) #把字典解开,host=127.0.0.1,port=3306,。。。。。
1 #局部变量和全局变量
2 #局部变量
3 #定义在函数里面变量,局部变量就只能在函数里面使用,出了函数外面就不能用了
4
5 name = 'abc'
6 def func():
7 name = 'abc2'
8 age=38 #定义了没有使用的变量 颜色就是灰色的
9 print('1',name)
10
11 func()
12 print('2',name)
13 print('2',age) #报错
14 #报错信息 NameError: name 'age' is not defined
15 运行结果:1 abc2
16 2 abc
17 -----------------------------------------------------------------------------------------------------------
18 #尽量避免少用全局变量
19 #1.只有python文件一直运行着 内存就一直占着
20 #2.全局变量谁都可以改 不安全
21 money = 0
22
23 def dsk():
24 global money #声明全局变量 要改全局变量的时候 才需要声明
25 money+=500
26
27 def ldd():
28 global money #声明全局变量
29 money-=1000
30
31 print('money之前的',money)
32 dsk()
33 print('挣钱之后的',money)
34 ldd()
35 print('花钱之后的',money)
36 运行结果:money之前的 0
37 挣钱之后的 500
38 花钱之后的 -500
39 ----------------------------------------------------------------------------------------------------------
40 练习题:
41 money = 500
42 def test(consume):#4.所以test(consume)=500
43 return money - consume #5.money - consume=500-500=0
44
45 def test1(money):# 2.所以test1接收到的money=500
46 return test(money) + money #6.返回的值是0+500=500
47 #3.test(money)中money接收到的值就是500
48 money = test1(money) #1.money=500 所以test1(money)=500 #7.函数返回500
49 print(money) #8.所以最后输出的还是500
50
51 ------------------------------------------------------------------------------------------------------------------
52 def test():
53 global a
54 a = 5
55
56 def test1():
57 c = a+5
58 return c
59
60 res = test1()
61 print(res)
62 运行结果:NameError: name 'a' is not defined 【报错】
63 分析:因为没有调用test(),所以相当于变量a没有被定义
64
65 :修改
66 def test():
67 global a
68 a = 5
69
70 def test1():
71 c = a+5
72 return c
73
74 test()
75 res = test1()
76 print(res)
77 运行结果:10
78 ------------------------------------------------------------------------------------------------------------
79 stus = ['xiaohei','xiaobai','yaya'] #列表 #不需要声明
80 stus_info = {
81 'name':'haha', #字典 #不需要声明
82 'age':18
83 }
84
85 stus2 = {'xiaoyg','hisui'} #集合 #不需要声明
86
87 #int str tuple #需要global声明
88
89 #可变类型:字典,list,set
90 #不可变类型:int,str,元组
91
92 def add_stu():
93 name = input('name:')
94 age = input('age:')
95 stus_info[name]=age
96
97 def select_stu():
98 name = input('name:')
99 print('你的学号是%s'%stus.index(name))
100
101 add_stu()
102 select_stu()
103
104 print(stus)
105 print(stus_info)
106 运行结果:name:huhu
107 age:32
108 name:yaya
109 你的学号是2
110 ['xiaohei', 'xiaobai', 'yaya']
111 {'name': 'haha', 'age': 18, 'huhu': '32'}
1 def xiaobai():
2 for i in range(100):
3 print(i)
4 return i
5
6 res = xiaobai()
7 print(res)
8 # #循环一次遇到return就结束了
9
10 def get_file(age,name,addr):
11 #当前目录下有多少个文件名
12 #这些文件的文件名
13 age+=5
14 name = 'szz_'+name
15 addr = 'beijing_'+addr
16 return age,name,addr #不管返回多少个参数,最后的结果都是放在一个元组里边
17 res = get_file(19,'xiaohei','昌平')
18 print(res)
19
20 age,name,addr=get_file(19,'xiaohei','昌平') #也可以给多个值来接收
21 print(age)
22 print(name)
23 print(addr)
24
25 # #在参数后面加冒号,代表传的参数是什么类型,就是方便调用方法
26 def add_user(username:str,password:list):
27 print(username)
28 print(password)
29
30 add_user('sd',{'sd':23}) #你传别的类型也不影响
31
32 #递归,函数自己调用自己
33
34 def a():
35 print('as')
36 a()
37
38 a()
39 #递归,函数自己调用函数,最深999次
40
41 def b():
42 num = input('请输入一个数字:').strip()
43 if int(num)%2!=0:
44 print('请重新输入:')
45 b()
46 b()