一、函数特性:
减少重复代码
使程序变得可扩展
使程序变得易扩展 定义语法:
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. SEO优化

    SEO是由英文Search Engine Optimization缩写而来, 中文意译为“搜索引擎优化”.SEO是指从自然搜索结果获得网站流量的技术和过程,是在了解搜索引擎自然排名机制的基础上, 对网 ...

  2. JQuery的一些简单操作01

    一.JQuery的隐藏和显示效果 1.hide/show/toggle hide隐藏效果,hide(1000)括号里面跟毫秒,show显示效果同样后面括号可以有数值,toggle开关按钮,交替作用隐藏 ...

  3. 怎么在excel中快速查找重复记录

    假设数字在A列,数字从A1开始:方法一:辅助列中输入公式,数据重复时会出现“重复”提示.=IF(COUNTIF(A:A,A1)>1,"重复","") ,下 ...

  4. chrome调试

    今天对chrome调试又进行了系统的学习. Chrome调试工具developer tool技巧 把以前没有使用过的功能列举一遍. 伪类样式调试:伪类样式一般不显示出来,比如像调试元素hover的样式 ...

  5. 黑马程序员:Java编程_7K面试题之交通灯管理系统

    =========== ASP.Net+Android+IOS开发..Net培训.期待与您交流!=========== 模拟实现十字路口的交通灯管理系统逻辑,具体需求如下: 异步随机生成按照各个路线行 ...

  6. 10道javascript笔试题

    1.考察this JavaScript var length = 10; function fn() { console.log(this.length); } var obj = { length: ...

  7. SQLAchemy、MYSQL、PYMYSQL

    什么是数据库? 个人理解:将一些有关系的数据组织在一起,并建立一定规则便于查询.修改.删除我们关系的数据仓库. 常用的数据库:mysql.oracle.sqlserver等. 接下来我们主要讲mysq ...

  8. python 字符串技巧 from python cookbook

    所有数据进入程序中都只是一串字节 英文字符占一个字节 汉语是两个字节 一字节byte=8bit Unicode字符串为每种语言的每种字符设定了统一并且唯一的二进制编码 big = r'This is ...

  9. C# DES进行加解密

    DES加解密 /// 进行DES加密. /// </summary> /// <param name="pToEncrypt">要加密的字符串.</p ...

  10. ThinkPHP 3.2 获取页面运行时间

    在ThinkPHP中,可以通过在config.php中配置'SHOW_PAGE_TRACE' =>true,打开页面调试,实现页面载入时间的显示.但显示在页面右下角TP的LOGO显然不能适用于我 ...