python05篇 json和函数
一、json
json就是一个字符串,只不过是所有语言能解析这个字符串。
1.1 把python的数据类型转为json
import json d = {'name': 'xiaohei', 'cars': [1, 2, 3], 'house': (4, 5, 6), 'addr': '北京'} # json就是一个字符串,只不过是所有语言能解析这个字符串 result = json.dumps(d) # 把python 的数据类型转json (list、tuple、dict) result2 = json.dumps(d, ensure_ascii=False, indent=4) # ensure_ascii:False会把带中文的显示出来 indent:可以加上缩进,更好识别去看 print(result2, type(result2)) # json.dump() # 将字典转成json,并写入文件中 with open('word.txt','w', encoding='utf-8') as fw: json.dump(d, fw, indent=4, ensure_ascii=False)
1.2 把json转为python的数据类型
import json # 把json转成 python 的数据类型(list、tuple、dict) json_str = '{"name": "xiaohei", "cars": [1, 2, 3], "house": [4, 5, 6],"addr":"\u5317\u4eac"}' dict2 = json.loads(json_str) print(dict2) # json.load()先读取文件内容,再将json转成字典 with open('word.txt', encoding='utf-8') as fr: d2 = json.load(fr)
二、函数
2.1 函数的定义
# 函数、方法 import string import datetime def hello(): # 定义函数,提高代码的复用性 print('hello') hello() # 函数调用 函数名() def baoshi(): print('now :', datetime.datetime.today()) # 函数返回值 # 函数没有写返回值时,默认返回None # return: # 1、返回数据 # 2、函数里只要遇到return 函数立马执行结束 def check_password(password): # 参数,位置参数 这里的参数叫做形参 password_set = set(password) if password_set & set(string.digits) and password_set & set(string.ascii_uppercase) \ and password_set & set(string.ascii_lowercase): return True else: return False password_result = check_password('12312321') # 这里传的参数叫做实参 print(password_result) baoshi()
2.2 函数的参数
import string import datetime def baoshi(): # 无参 print('now :', datetime.datetime.today()) def check_password(password): # 必填参数,位置参数 pass def op_file(file_name,content = None): # 如果传参取传参的值,没传取默认值 pass if content: write_file(file_name, content) else: result = read_file(file_name) return result print(op_file('2.txt')) op_file('2.txt', 'slskfslls两节课') # 可选参数,它不是必传的,不限制参数个数,它是把参数放到了一个list中 def send(*args): for p in args: print('发短信给xxx%s' % p) send() send(110) send(110, 112, 119) # 关键字参数,它不是必传的,不限制参数个数.它是把参数放到了一个字典里面 # 传参必须是关键字的方式,key=value def send_sms(**kwargs): print(kwargs) send_sms() send_sms(xiaolan = '晚上好') send_sms(xiaobai='新年好', xiaohei='生日快乐', xiaozi='') # 四种参数都用上的顺序:1.必填参数 2. 默认值参数 3. 参数组 4. 关键字参数 def dc_func(name,age,country='China',sex='女',*agrs,**kwargs): pass # name = 'xh' age=18 country = 'abc' sex = 'efg' ('hhh',)传参给参数组 names=1, b=2, c=3 作为字典{'names': 1, 'b': 2, 'c': 3}传参给关键字参数 dc_func('xh', 18, 'abc', 'efg', 'hhh',names=1, b=2, c=3) # name = 'xh' age=18 country = 'abc' sex = 'efg' ('hhh','2335','23532')传参给参数组 dc_func('xh', 18, 'japan', 'nan', 'abc', 'efg', 'hhh', '2335', '23532') def hhh(name, age, sex): print(name) print(age) print(sex) l = ['xh', 18, 'nan'] hhh(*l) # 拆包传参,但是参数个数要对应上,不能多 d = {'name': 'xiaohei', 'age': 18, 'sex': 'nam'} hhh(**d) # 字典的key与函数中的参数名称一致的情况下,可以这么传参
2.3 函数的返回
# 如果一个函数没有返回值的,返回None def test(): print('hello') # 如果一个函数返回值是多个的,返回的是元组,也可以用多个参数接受返回值(拆包) def test2(): return 1, 2, 3 print(test()) a, b, c = test2() # 也可以用多个参数接受返回值(拆包) print(test2()) # 全局变量:一般定义在代码的最上面,大家都可以用,是公共的变量。全局变量一直占用内存 # 局部变量:在函数里面定义的变量,都是局部变量.函数中优先找函数内部的变量,没有再去找全局变量 # 函数中的变量的作用域是在函数内,局部变量在函数调用完后就消失掉 country = 'China' file_name = 'b.txt' # list dict set 不需要用global来声明 # str int float tuple bool 需要声明 def say(): print(country) def xiaoba(): country = 'Japan' def update_file_name(): global file_name # 申明这里的变量是全局变量 file_name = 'c.json' # 全局变量不定义,放在函数中使用global,只用函数被调用在会声明变量,如果未声明就在其他函数中使用会报错
2.4 函数小练习
# 判断小数 # ‘1.5’ # 传参 包含. 其他均是数字 def is_float(num=0): num = str(num) if num.count('.') == 1: left, right = num.split('.') if left.isdigit() and right.isdigit(): return True # if left.startswith('-') and left.lstrip('-') and right.isdigit(): if left[0] == '-' and left.lstrip('-') and right.isdigit(): return True return False
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)