• 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":"u5317u4eac"}'
    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
     
  • 相关阅读:
    随笔程序能干啥?
    Net C# 扩展方法
    iOS中控制器的实践和学习(4)简易5图之A4
    简单的程序员
    阅读iPhone.3D.ProgrammingHelloArrow项目
    有感 阅读iPhone.3D.ProgrammingHelloArrow项目
    WebResource.axd
    [转]ASP.NET AJAX clientside framework failed to load
    BinConvertor
    [转]ASP.NET AJAX and Sys.Webforms.PageRequestManagerServerErrorException
  • 原文地址:https://www.cnblogs.com/lhy-qingqiu/p/13574342.html
Copyright © 2020-2023  润新知