内容简介:函数也称方法,是用于实现特定功能的一段代码函数用于提高代码的复用性函数必须要调用才会执行
函数也称方法,是用于实现特定功能的一段代码
函数用于提高代码的复用性
函数必须要调用才会执行
函数里面定义的变量,为局部变量,局部变量只在函数里面可以使用,出了函数外面之后就不能使用
一个函数只做一件事情
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、实现一个商品管理的程序。 #输出1,添加商品 2、删除商品 3、查看商品 添加商品: 商品的名称:xxx 商品如果已经存在的话,提示商品商品已经存在 商品的价格:xxxx 数量只能为大于0的整数 商品的数量:xxx,数量只能为大于0的整数 2、删除商品: 输入商品名称: iphone 如果输入的商品名称不存在,要提示不存在 3、查看商品信息: 输入商品名称: 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))
拷贝
浅拷贝,内存地址不变,把两个对象指向同一份内容,
深拷贝,会重新在内存中生成相同内容的变量
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
校验小数类型
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
参数
位置参数
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有序
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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Head First JavaScript Programming
Eric T. Freeman、Elisabeth Robson / O'Reilly Media / 2014-4-10 / USD 49.99
This brain-friendly guide teaches you everything from JavaScript language fundamentals to advanced topics, including objects, functions, and the browser’s document object model. You won’t just be read......一起来看看 《Head First JavaScript Programming》 这本书的介绍吧!