一、函数特性:
减少重复代码
使程序变得可扩展
使程序变得易扩展 定义语法:
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)
四、应用实例:

现需要对这个员工信息文件,实现增删改查操作

  1. 可进行模糊查询,语法至少支持下面3种:
    1.   select name,age from staff_table where age > 22
    2.   select  * from staff_table where dept = "IT"
    3. select  * from staff_table where enroll_date like "2013"
    4. 查到的信息,打印后,最后面还要显示查到的条数
  2. 可创建新员工纪录,以phone做唯一键,staff_id需自增
  3. 可删除指定员工信息纪录,输入员工id,即可删除
  4. 可修改员工信息,语法如下:
  5.   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函数的更多相关文章

  1. Python之旅Day4 闭包函数 模块及模块倒入

    闭包函数 闭包函数就是在内部函数当中有对外部函数名字的引用 ###代码示例1### def f1(): x =1 def f2(): print(x) return f2 f=f1() f() ### ...

  2. 用python实现矩阵转置,python3 中zip()函数

    前几天群里有同学提出了一个问题:手头现在有个列表,列表里面两个元素,比如[1, 2],之后不断的添加新的列表,往原来相应位置添加.例如添加[3, 4]使原列表扩充为[[1, 3], [2, 4]],再 ...

  3. python函数应用

    函数 定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编 ...

  4. python函数 位置参数,关键字参数,可变参数优先级

    def fun(arg,args=1,*arg,**keywords): python 一共有这四类参数,第一类最常见,不用多说,第二类,关键字参数,python能通过关键字找到参数,python函数 ...

  5. Python之路,Day4 - Python基础4 (new版)

    Python之路,Day4 - Python基础4 (new版)   本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 ...

  6. Day4 - Python基础4 迭代器、装饰器、软件开发规范

    Python之路,Day4 - Python基础4 (new版)   本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 ...

  7. [Python_3] Python 函数 & IO

    0. 说明 Python 函数 & IO 笔记,基于 Python 3.6.2 参考  Python: read(), readline()和readlines()使用方法及性能比较  Pyt ...

  8. python3 的 round 函数的 练习

    python3 的 round 函数感觉很别扭,其运算结果与习惯不相符.特记录下来: 代码 ''' python 3的 round 函数 是"四舍六入五成双"的 https://w ...

  9. python3内置函数大全(顺序排列)

    python3内置函数大全 内置函数 (1)abs(),   绝对值或复数的模 1 print(abs(-6))#>>>>6 (2)all() 接受一个迭代器,如果迭代器的所有 ...

  10. python3内置函数大全

    由于面试的时候有时候会问到python的几个基本内置函数,由于记不太清,就比较难受,于是呕心沥血总结了一下python3的基本内置函数 Github源码:        https://github. ...

随机推荐

  1. 安装ant问题

    1  设置path, 在windwos 7下要重启 2  重启后,cmd----ant -version  Unable to locate tools.jar. Expected to find i ...

  2. Spring中的IOC\DI\AOP等概念的简单学习

    IoC(Inversion of Control,控制反转).这是spring的核心,贯穿始终, 所谓IoC,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系.Spr ...

  3. 感知机的对偶形式——python3实现

    运用对偶的(对应原始)感知机算法实现线性分类. 参考书目:<统计学习方法>(李航) 算法原理: 代码实现: 环境:win7 32bit + Anaconda3 +spyder 和原始算法的 ...

  4. Android ——单元测试

    什么是单元测试 首先需要介绍一下什么是单元测试.很多人像我一样,本科并不是计算机专业出身的,如果在职的公司不要求做单元测试的话,可能对这个词并没有一个确切的概念.而即使是计算机专业出身,如果毕业以后写 ...

  5. [搬砖]Pycharm中启动IPython notebook失败提示load_entry_point ImportError: Entry point ('console_scripts', 'ipython') not found的解决方法

    前提:直接运行ipython正常,“which -a ipython”命令显示也只有一个ipython存在,在ipynb文件中点运行启动notebook时提示错误类似如下: Traceback (mo ...

  6. iOS工作小技巧及填坑记录

    以下是本人在iOS开发工作中使用的一些小技巧,记录一下. 1.使用XXX.pch文件便捷开发+加速Build 在IOS开发的项目中有一个XX_Prefix.pch XX_Prefix.pch:扩展名. ...

  7. MeshDog

    一.TransforMesh 1. CGAL (http://www.cgal.org/download/windows.html#GeneralPrerequisites) 预装软件 1.1 cma ...

  8. MSSQL—列记录合并

    在项目开发中,有时会碰到将列记录合并为一行的情况,例如根据地区将人员姓名合并,或根据拼音首字母合并城市等,下面就以根据地区将人员姓名合并为例,详细讲一下合并的方法. 首先,先建一个表,并添加一些数据, ...

  9. Reconstruct Itinerary

    Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...

  10. 修改VS 所有项目的Include目录和Lib目录

    像以前的方法 在 工具--选项--项目和解决方案里的修改已经被弃用.