1. 程式人生 > 實用技巧 >python05篇 json和函式

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