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. ...
随机推荐
- 用springMVC构建restful程序,接收以及返回json数据格式
主要参考文章:http://kingxss.iteye.com/blog/1487745和http://blog.csdn.net/greensurfer/article/details/192962 ...
- 本地测试AJAX请求
要在本地测试AJAX,首先是环境的搭建,因为XHR对象的open方法中参数url是指文件在服务器上的文件.下面以WampServer为例. 1. 下载wamp的安装包,下载地址为:http://221 ...
- SQL盲注之正则攻击
我们都已经知道,在MYSQL 5+中 information_schema库中存储了所有的 库名,表明以及字段名信息.故攻击方式如下: 1. 判断第一个表名的第一个字符是否是a-z中的字符,其中bli ...
- BZOJ3669 (动态树)
Problem 魔法森林 (NOI2014) 题目大意 给n个点,m条边的无向图,每条边有两个权值a,b. 求一条从1-->n的路径,使得这条路径上max(a)+max(b)最小.输出最小值即可 ...
- js完美身份证验证
/*根据[中华人民共和国国家标准 GB 11643-1999]中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成.排列顺序从左至右依次为:六位数字地址码,八位数 ...
- CoInitialize浅析一
大家都知道程序中若要使用COM组件则必须要先调用CoInitialize,该函数主要是用来初始化COM运行环境.但这个函数的作用域是以线程为单位还是以进程为单位呢?也许大家已经通过测试程序摸索出答案, ...
- thinkphp 介绍
一.ThinkPHP的介绍 MVC M - Model 模型 工作:负责数据的操作 V - View 视图(模板) 工作:负责 ...
- EtherType
EtherType is a two-octet field in an Ethernet frame. It is used to indicate which protocol is encaps ...
- mysql二进制文件操作语法(mysql binary log operate statements)
开启 binary logs 功能 在 mysql 配置文件中配置 log-bin,重启 mysql my.cnf (on Linux/unix) or my.ini (on Windows) 例子: ...
- tcp之快速重传与恢复
本文为原创,转载请注明:http://www.cnblogs.com/gistao/ Background 写网络程序的都知道,tcp的窗口控制分为慢启动阶段和拥塞避免阶段,重传机制有快速重传/恢复和 ...
