python3-day4-python函数
一、函数特性:
减少重复代码
使程序变得可扩展
使程序变得易扩展 定义语法:
def sayhi():
print("hello")
return
sayhi() def sayhi(name):
print("hello %s" % name)
return
sayhi("alex")
二、函数参数
1、关键字参数
def sayhi():
print("hello")
return
sayhi() def sayhi(name):
print("hello %s" % name)
return
sayhi("alex")
2、默认参数
def sayhi(name,age,job="IT"):
print("hello %s %s %s" % name,age,job)
return
sayhi(22,name="alex")
3、位置参数
def sayhi(name,age,job="IT"):
print("hello %s %s %s" % name,age,job)
return
sayhi(22,name="alex")
4、非固定参数:arge:*元祖,kargs:**字典 ,a=1 是字典, 单纯的字符串为元祖
def sayhi(name,age,job="IT",*arge,*kwargs*):
print("hello %s %s %s" % name,age,job)
print("other arguments:",arge.kargws)
return
sayhi(22,name="alex")
三、函数变量
1、局部变量:
只在函数内部生效
def sayhi(name,age,job="IT",*arge,*kwargs*):
print("hello %s %s %s" % name,age,job)
print("other arguments:",arge.kargws)
a=123#局部变量
return
sayhi(22,name="alex")
2、返回值:
1、返回值:一旦函数经过调用并开始执行,那函数外部的程序就没有办法在控制函数的执行过程,
此时外部程序只能等待函数执行结果,因为外部程序要根据执行结果来决定下一步怎么走,
这个执行结果就是以return的形式返回给外部。
2、return代表着一个函数的结束。
3、return可以返回任意数据类型。
4、return对于用户来讲,可以返回多个任意数量的值,对于python来讲,函数只能返回一个值,多个值会转成元祖(1,2,3,4,5) 3、嵌套函数:
def sayhi(name,age):
print("hello %s %s" % name,age)
def sayhi2():
print("caocao")
sayhi2()
sayhi()
4、递归:
特性:
1、必须有一个明确的结束条件
2、每次进入更深一层递归时,为题规模相比上次递归都应相应减少
3、递归效率不高,递归层次过多会导致栈溢出 5、匿名函数:
def calc(n):
return n*n
calc2=lambda x:x*x #匿名函数
print(calc(8)) map 把列表的值带入函数进行运算
6、三元运算:a=4 b=5
d=a if a>10 else b
if a>10 :
d=a
else:
d=b
d=5
7、高阶函数:
变量可以指向函数,在函数中调用变量就等于调用函数,这种方法就叫高阶函数
abs:求绝对值 8、内置函数:
1)chr(98) 打印数字对应的assic码
2)ord(a) 打印字母对应的assic码 3)
d=a if a>10 else b
if a>10 :
d=a
else:
d=b
d=5
4)eval("4+4")#做简单运算 5)dict()字典
6)dir()显示调用方法
7)divmod(10,2)返回商和余
8)filter(lambda x:x>5,range(10)) 过滤满足条件的值
9)globals()以字典的形式打印当前内存中所有的全局变量
10)locals()以字典的形式打印当前内存中的所有局部变量(在函数中)
11)hex()求16进制 0x表示
12)id()求内存地址
13)max()求列表中最大值
14)min()求最小值
15)oct()求8进制 0o表示
16)pow()求x**y幂
17)reversed(data)#反转列表,字符串
18)round((10.26,1))四舍五入
19)set(data),将列表转换成集合
20)slice 等于切片
pattern= slice(3,8,2)
21)sorted()按照assic对字符串进行排序
22)sum()列表求和
23)vars()跟globals一样
24)zip()#拉链作用,两个列表一一对应
a=[1,3,5,7]
b=[2,4,6,8]
for i in zip(a,b):
print(i)
四、应用实例:
现需要对这个员工信息文件,实现增删改查操作
- 可进行模糊查询,语法至少支持下面3种:
- select name,age from staff_table where age > 22
- select * from staff_table where dept = "IT"
- select * from staff_table where enroll_date like "2013"
- 查到的信息,打印后,最后面还要显示查到的条数
- 可创建新员工纪录,以phone做唯一键,staff_id需自增
- 可删除指定员工信息纪录,输入员工id,即可删除
- 可修改员工信息,语法如下:
- UPDATE staff_table SET dept="Market" WHERE where dept = "IT"
文件信息如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# user:slim_liu
#date:2016-10-31
def select(user_input):
id = user.index("where") + 1
where = user[id:] # 查询的条件
sel = user.index("select") + 1
fro = user.index("from")
sele = user[sel:fro] # 查询的内容
ste = ''.join(sele)
set = ste.split(",")
inde = []
count = 0
tiaojian = where[0] + " " + where[1] + " " + where[2]
if where[1] == "=":
tiaojian = tiaojian.replace("=", "==")
if "*" not in ste:
for y in set:
inde.extend(str(lie.index(y)))
if "like" not in where:
for i in f:
line = i.strip().split(",")
staff_id = int(line[0])
name = line[1]
age = int(line[2])
phone = str(line[3])
dept = str(line[4])
enroll_date = str(line[5])
if eval(tiaojian):
for x in set:
if x in lie:
print(line[lie.index(x)], line[int(inde[1])])
count += 1
break
else:
print(line)
count += 1
print("共匹配到", count, "条数据")
else:
for i in f:
line = i.strip().split(",")
staff_id = int(line[0])
name = line[1]
age = int(line[2])
phone = str(line[3])
dept = str(line[4])
enroll_date = str(line[5])
if "like" in where:
if str(where[2]).strip('''"''') in enroll_date:
print(line)
else:
continue
count += 1
print("共匹配到", count, "条数据") def update(user_input):
id = user.index("where") + 1
where = user[id:] # 修改后的内容
sel = user.index("set") + 1
fro = user.index("where")
sele = user[sel:fro] # 被修改的内容
# ste = ''.join(sele)
# set = ste.split(",")
mubiao = where[0] + " " + where[1] + " " + where[2]
tiaojian = sele[0] + " " + sele[1] + " " + sele[2]
if where[1] == "=":
tiaojian = tiaojian.replace("=", "==")
if sele[1] == "=":
mubiao = mubiao.replace("=", "==")
k = open("user1", "w+", encoding="utf-8")
for i in f:
line = i.strip().split(",")
staff_id = int(line[0])
name = line[1]
age = int(line[2])
phone = str(line[3])
dept = str(line[4])
enroll_date = str(line[5])
if eval(tiaojian):
i = i.replace(str(sele[2]).strip('''"'''), str(where[2].strip('''"''')))
print(i.strip(), file=k)
print("信息更新成功:", i.strip())
else:
print(line[0] + "," + line[1] + "," + line[2] + "," + line[3] + "," + line[4] + "," + line[5] + ",", file=k) k.close()
j = open("user1", encoding="utf-8")
k = open("user", "w+", encoding="utf-8")
for i in j:
print(i.strip(), file=k)
k.close() def insert(user_input):
ID = 1
phone_list = []
t = open("user", "a+", encoding="utf-8")
id = user.index("values") + 1
where = user[id:] # 插入的值
le = len(where)
print(le)
if le == 4:
ste = ''.join(where)
set = ste.strip(''')"("''').split(" ")
set2 = str(set[0]).split(",")
for y in f:
ID += 1
phon = y.strip().split(",")
phone_list.append(phon[3])
if set2[2].strip("""'""") in phone_list:
print("手机号码已存在,添加失败!")
else:
print(str(ID) + "," + set2[0].strip("""'""") + "," + set2[1].strip("""'""") + "," + set2[2].strip(
"""'""") + "," + set2[3].strip("""'""") + "," + set2[4].strip("""'"""), file=t)
print("添加成功,本次添加1条")
print(str(ID) + "," + set2[0].strip("""'""") + "," + set2[1].strip("""'""") + "," + set2[2].strip(
"""'""") + "," + set2[3].strip("""'""") + "," + set2[4].strip("""'"""))
t.close()
else:
print("您输入的格式有误,例:[name", "age", "phone", "dept", "enroll_date],请重新输入:") def delete(user_input):
ID = 0
id = user.index("where") + 1
where = user[id:] # 删除的条件
tiaojian = where[0] + " " + where[1] + " " + where[2]
if where[1] == "=":
tiaojian = tiaojian.replace("=", "==")
r = open("user1", "w+", encoding="utf-8")
for i in f:
ID += 1
line = i.strip().split(",")
staff_id = int(line[0])
if eval(tiaojian):
print("删除成功:",line)
line.clear()
else:
print(line[0] + "," + line[1] + "," + line[2] + "," + line[3] + "," + line[4] + "," + line[5] + ",", file=r)
r.close()
j = open("user1", encoding="utf-8")
k = open("user", "w+", encoding="utf-8")
id2 = 0
for i in j:
id2 += 1
e = i.split(",")
i = i.replace(str(e[0]), str(id2))
print(i.strip(), file=k)
k.close() while True:
user_input = input("cmbh >>")
f = open('user', encoding="utf-8")
lie = ["staff_id", "name", "age", "phone", "dept", "enroll_date"]
where = ["staff_id", "name", "age", "phone", "dept", "enroll_date", "=", ">=", "<=", ">", "<", "运维", "IT", "SA","无"]
user = user_input.split(" ") if "select" in user:select(user_input)
elif "insert" in user:insert(user_input)
elif "delete" in user:delete(user_input)
elif "update" in user:update(user_input)
elif "quit" in user or "exit" in user:exit()
else:print("您的输入有误,请从新输入:")
python3-day4-python函数的更多相关文章
- Python之旅Day4 闭包函数 模块及模块倒入
闭包函数 闭包函数就是在内部函数当中有对外部函数名字的引用 ###代码示例1### def f1(): x =1 def f2(): print(x) return f2 f=f1() f() ### ...
- 用python实现矩阵转置,python3 中zip()函数
前几天群里有同学提出了一个问题:手头现在有个列表,列表里面两个元素,比如[1, 2],之后不断的添加新的列表,往原来相应位置添加.例如添加[3, 4]使原列表扩充为[[1, 3], [2, 4]],再 ...
- python函数应用
函数 定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编 ...
- python函数 位置参数,关键字参数,可变参数优先级
def fun(arg,args=1,*arg,**keywords): python 一共有这四类参数,第一类最常见,不用多说,第二类,关键字参数,python能通过关键字找到参数,python函数 ...
- Python之路,Day4 - Python基础4 (new版)
Python之路,Day4 - Python基础4 (new版) 本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 ...
- Day4 - Python基础4 迭代器、装饰器、软件开发规范
Python之路,Day4 - Python基础4 (new版) 本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 ...
- [Python_3] Python 函数 & IO
0. 说明 Python 函数 & IO 笔记,基于 Python 3.6.2 参考 Python: read(), readline()和readlines()使用方法及性能比较 Pyt ...
- python3 的 round 函数的 练习
python3 的 round 函数感觉很别扭,其运算结果与习惯不相符.特记录下来: 代码 ''' python 3的 round 函数 是"四舍六入五成双"的 https://w ...
- python3内置函数大全(顺序排列)
python3内置函数大全 内置函数 (1)abs(), 绝对值或复数的模 1 print(abs(-6))#>>>>6 (2)all() 接受一个迭代器,如果迭代器的所有 ...
- python3内置函数大全
由于面试的时候有时候会问到python的几个基本内置函数,由于记不太清,就比较难受,于是呕心沥血总结了一下python3的基本内置函数 Github源码: https://github. ...
随机推荐
- NPOI 单元格(cell) 格式参数
NPOI 单元格(cell) 将格式设为文本 在网上找了很久,都没有关于如何设置的信息,没办法查了下NPOI的源码终于找到了方法.这里共享下,就是“@”参数 ICellStyle cellStyle ...
- Java命名规则总结
1. JAVA源文件的命名 JAVA源文件名必须和源文件中所定义的类的类名相同. 2. Package的命名 Package名的第一部分应是小写ASCII字符,并且是顶级域名之一,通常是com.edu ...
- 2016-08-05(1) ng-options的用法详解
http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/ng-options-usage/
- MyEclipse 10.7.1 最新版官网下载地址
MyEclipse 10.7.1(Windows): http://downloads.myeclipseide.com/downloads/products/eworkbench/indigo/in ...
- 机器学习之分类器性能指标之ROC曲线、AUC值
分类器性能指标之ROC曲线.AUC值 一 roc曲线 1.roc曲线:接收者操作特征(receiveroperating characteristic),roc曲线上每个点反映着对同一信号刺激的感受性 ...
- jquery.extend方法
jquery.extend()用来扩展jquery中方法,实现插件. 1.jQuery.extend函数详细用法! 扩展jQuery静态方法. 1$.extend({ 2test:function() ...
- hibernate 中createQuery与createSQLQuery两个用法
hibernate 中createQuery与createSQLQuery两者区别是:前者用的hql语句进行查询,后者可以用sql语句查询前者以hibernate生成的Bean为对象装入list返回后 ...
- Chrome和IE中使用window.open函数
做前端开发的人员经常回遇到使用windows.open这个函数来打开一个新的网页窗口,使用这个函数的时候有些需要注意的地方,在Chrome和IE下该函数还是有一些细节性的区别. 以下是我在项目中使用的 ...
- Java高级规范之二
二十一.提交java代码前应该检查是否有没用的语句,如:System.out.println(); jsp页面上面是否有alert调试信息 不规范示例:暂无 规范实例:暂无 解析:因为如果保留了有可能 ...
- Python 基礎 - 字典的操作使用
接下來介紹字典,這在未來工作上,會是很常使用的,就來好好了解一下唄- 字典是一個 key(鍵)-value(值) 的數據類型,可以儲存很多訊息 #!/usr/bin/env python3 # -*- ...