函数也称方法,是用于实现特定功能的一段代码
函数用于提升代码的复用性
函数必需要调用才会执行
函数里面定义的变量,为局部变量,局部变量只在函数里面可使用,出了函数外面以后就不能使用
一个函数只作一件事情git
import json def get_file_content(file_name): #形参 #入参:传入一个文件名 #返回:文件内容转成字典并返回 with open(file_name, encoding='utf-8') as f: res = json.load(f) return res abc = 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,添加商品 二、删除商品 三、查看商品 添加商品: 商品的名称:xxx 商品若是已经存在的话,提示商品商品已经存在 商品的价格:xxxx 数量只能为大于0的整数 商品的数量:xxx,数量只能为大于0的整数 二、删除商品: 输入商品名称: iphone 若是输入的商品名称不存在,要提示不存在 三、查看商品信息: 输入商品名称: iphone: 价格:xxx 数量是:xxx all: print出全部的商品信息 ''' FILENAME = 'products.json' import json def 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 res def 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 0 def 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))
浅拷贝,内存地址不变,把两个对象指向同一分内容,
深拷贝,会从新在内存中生成相同内容的变量json
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 copy l = [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 json def 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
校验小数类型iphone
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 False print(check_float('1.1'))
def te(): global a a = 5 def te1(): c = a + 5 return c res = te1() print(res) #代码会报错,te()中定义的a在函数没被调用前不能使用
money = 500 def t(consume): return money - consume def t1(money): return t(money) + money money = 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() #wangcai get_name() #hailong print('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
位置参数code
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,默认参数 #可变参数 #关键字参数 pass def 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有序ip
l = [1,1,2,2,3,3,3] res = set(l) #将list转为set l = list(res) #set去重后转为list print(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 ^ zdh print(res)
import string l1 = 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,无则True l2.add('s') #添加元素 print(l2) print(l2.pop()) #随机删除一个元素 l2.remove('a') #删除指定元素 for l in l2: print(l)