函数也称方法,是用于实现特定功能的一段代码
函数用于提高代码的复用性
函数必须要调用才会执行
函数里面定义的变量,为局部变量,局部变量只在函数里面可以使用,出了函数外面之后就不能使用
一个函数只做一件事情
import jsondef get_file_content(file_name): #形参 #入参:传入一个文件名 #返回:文件内容转成字典并返回 with open(file_name, encoding='utf-8') as f: res = json.load(f) return resabc = get_file_content('stus.json') #函数调用才执行,此处传入实参,函数有返回,需要用变量接收print(abc)
def write_file(filename,content): with open(filename,'w', encoding='utf-8') as f: #f.write(json.dumps(content)) json.dump(content,f,ensure_ascii=False,indent=4)dict = {'name':'wrp','age':'18'}write_file('wrp.json',dict)
'''作业: 1、实现一个商品管理的程序。 #输出1,添加商品 2、删除商品 3、查看商品 添加商品: 商品的名称:xxx 商品如果已经存在的话,提示商品商品已经存在 商品的价格:xxxx 数量只能为大于0的整数 商品的数量:xxx,数量只能为大于0的整数 2、删除商品: 输入商品名称: iphone 如果输入的商品名称不存在,要提示不存在 3、查看商品信息: 输入商品名称: iphone: 价格:xxx 数量是:xxx all: print出所有的商品信息 '''FILENAME = 'products.json'import jsondef get_file_content(): with open(FILENAME, encoding='utf-8') as f: content = f.read() if len(content) > 0: res = json.loads(content) else: res = {} return resdef write_file_content(dict): with open(FILENAME,'w',encoding='utf-8') as fw: json.dump(dict, fw, indent=4, ensure_ascii=False)def check_digit(st:str): if st.isdigit(): st = int(st) if st > 0: return st else: return 0 else: return 0def add_product(): product_name = input("请输入商品名称:").strip() count = input("请输入商品数量:").strip() price = input("请输入商品价格:").strip() all_products = get_file_content() if check_digit(count) == 0: print("数量输入不合法") elif check_digit(price) == 0: print("价格输入不合法") elif product_name in all_products: print("商品已经存在") else: all_products[product_name] = {"count":int(count),"price":int(price)} write_file_content(all_products) print("添加成功")def del_product(): product_name = input("请输入要删除的商品名称:").strip() all_products = get_file_content() if product_name in all_products: all_products.pop(product_name) print("删除成功") write_file_content(all_products) else: print("商品不存在")def show_product(): product_name = input("请输入要查询的商品名称:").strip() all_products = get_file_content() if product_name == 'all': print(all_products) elif product_name not in all_products: print("商品不存在") else: print(all_products.get(product_name))
拷贝
浅拷贝,内存地址不变,把两个对象指向同一份内容,
深拷贝,会重新在内存中生成相同内容的变量
l = [1,1,1,2,3,4,5]l2 = l #浅拷贝#l2 = l.copy() #浅拷贝 for i in l2: if i % 2 != 0: l.remove(i)print(l)#在此程序中,如果对同一个list进行遍历并删除,会发现结果和预期不一致,结果为[1,2,4],使用深拷贝就没问题
import copyl = [1,1,1,2,3,4,5]l2 = copy.deepcopy(l) # 深拷贝for i in l2: if i % 2 != 0: l.remove(i)print(l)
非空即真,非零即真
name = input('请输入名称:').strip()name = int(name) #输入0时为假if name: print("输入正确")else: print("name不能为空")
默认参数
import jsondef op_file_tojson(filename, dict=None): if dict: #如果dict传参,将json写入文件 with open(filename,'w',encoding='utf-8') as fw: json.dump(dict,fw) else: #如果没传参,将json从文件读出 f = open(filename, encoding='utf-8') content = f.read() if content: res = json.loads(content) else: res ={} f.close() return res
校验小数类型
def check_float(s): s = str(s) if s.count('.') == 1: s_split = s.split('.') left, right = s_split if left.isdigit() and right.isdigit(): return True elif left.startswith('-') and left[1:].isdigit and right.isdigit(): return True else: return False else: return Falseprint(check_float('1.1'))
全局变量
def te(): global a a = 5 def te1(): c = a + 5 return cres = te1()print(res) #代码会报错,te()中定义的a在函数没被调用前不能使用
money = 500def t(consume): return money - consumedef t1(money): return t(money) + moneymoney = t1(money)print(money) #结果为500
name = 'wangcai'def get_name(): global name name = 'hailong' print('1,函数里面的name', name)def get_name2(): print('2,get_name2', name)get_name2() #wangcaiget_name() #hailongprint('3,函数外面的name', name) #hailong
递归
递归的意思是函数自己调用自己
递归最多递归999次
def te1(): num = int(input('please enter a number:')) if num%2==0: #判断输入的数字是不是偶数 return True #如果是偶数的话,程序就退出,返回True print('不是偶数,请重新输入') return te1()#如果不是的话继续调用自己,输入值print(te1()) #调用test1
参数
位置参数
def db_connect(ip, user, password, db, port): print(ip) print(user) print(password) print(db) print(port)db_connect(user='abc', port=3306, db=1, ip='192.168.1.1', password='abcde')db_connect('192.168.1.1','root', db=2, password='123456', port=123)#db_connect(password='123456', user='abc', 2, '192.168.1.1', 3306) #方式不对,位置参数的必须写在前面,且一一对应,key=value方式必须写在后面
可变参数
def my(name, sex='女'): #name,必填参数,位置参数 #sex,默认参数 #可变参数 #关键字参数 passdef send_sms(*args): #可变参数,参数组 #1.不是必传的 #2.把传入的多个元素放到了元组中 #3.不限制参数个数 #4.用在参数比较多的情况下 for p in args: print(p)send_sms()send_sms(123456)send_sms('123456','45678')
关键字参数
def send_sms2(**kwargs): #1.不是必传 #2.不限制参数个数 #3.key=value格式存储 print(kwargs)send_sms2()send_sms2(name='xioahei',sex='nan')send_sms2(addr='北京',county='中国',c='abc',f='kkk')
集合
集合,天生可以去重
集合无序,list有序
l = [1,1,2,2,3,3,3]res = set(l) #将list转为setl = list(res) #set去重后转为listprint(res)print(l)set = {1,2,3} #set格式jihe = set() #定义一个空的集合xn=['tan','yang','liu','hei']zdh=['tan','yang','liu','jun','long']xn = set(xn)zdh = set(zdh)# res = xn.intersection(zdh) #取交集# res = xn & zdh #取交集res = xn.union(zdh) #取并集res = xn | zdh #取并集res = xn.difference(zdh) #取差集,在A中有,在B中无的res = xn - zdh #取差集res = xn.symmetric_difference(zdh) #对称差集,取两个中不重合的数据res = xn ^ zdhprint(res)
import stringl1 = set(string.ascii_lowercase)l2 = {'a','b','c'}print(l2.issubset(l1)) #l2是不是l2的子集print(l2.issuperset(l1)) #l2是不是l2的父集print(l2.isdisjoint(l1)) #是否有交集,有则Flase,无则Truel2.add('s') #添加元素print(l2)print(l2.pop()) #随机删除一个元素l2.remove('a') #删除指定元素for l in l2: print(l)