Python基礎-函數

函數也稱方法,是用於實現特定功能的一段代碼
函數用於提升代碼的複用性
函數必需要調用纔會執行
函數裏面定義的變量,爲局部變量,局部變量只在函數裏面可使用,出了函數外面以後就不能使用
一個函數只作一件事情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)
相關文章
相關標籤/搜索